#!/usr/bin/env bash

# import common functions
source "$FRAMEWORK_PATH/utils/bridges.sh"

# Expected sovereign accounts.
#
# Generated by:
#
##[test]
#fn generate_sovereign_accounts() {
#	use polkadot_parachain_primitives::primitives::Sibling;
#	use sp_core::crypto::Ss58Codec;
#	use staging_xcm_builder::{GlobalConsensusConvertsFor, SiblingParachainConvertsVia};
#	use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH};
#	use xcm_executor::traits::ConvertLocation;
#
#	const Rococo: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH);
#	const Westend: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
#	frame_support::parameter_types! {
#		pub UniversalLocationAHR: InteriorLocation = [GlobalConsensus(Rococo), Parachain(1000)].into();
#		pub UniversalLocationAHW: InteriorLocation = [GlobalConsensus(Westend), Parachain(1000)].into();
#	}
#
#	// SS58=42
#	println!("ASSET_HUB_WESTEND_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WESTEND=\"{}\"",
#			 frame_support::sp_runtime::AccountId32::new(
#				 SiblingParachainConvertsVia::<Sibling, [u8; 32]>::convert_location(
#					 &Location { parents: 1, interior: Parachain(1000).into() }).unwrap()
#			 ).to_ss58check_with_version(42_u16.into())
#	);
#
#	// SS58=42
#	println!("ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO=\"{}\"",
#			 frame_support::sp_runtime::AccountId32::new(
#				 SiblingParachainConvertsVia::<Sibling, [u8; 32]>::convert_location(
#					 &Location { parents: 1, interior: Parachain(1000).into() }).unwrap()
#			 ).to_ss58check_with_version(42_u16.into())
#	);
#}
ASSET_HUB_WESTEND_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WESTEND="5Eg2fntNprdN3FgH4sfEaaZhYtddZQSQUqvYJ1f2mLtinVhV"
ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO="5Eg2fntNprdN3FgH4sfEaaZhYtddZQSQUqvYJ1f2mLtinVhV"
BOB_ACCOUNT_AT_ROCOCO="5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"
BOB_ACCOUNT_AT_WESTEND="5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"

# Expected sovereign accounts for rewards on BridgeHubs.
#
# Generated by:
##[test]
#fn generate_sovereign_accounts_for_rewards() {
#	use bp_messages::LegacyLaneId;
#	use bp_relayers::{PayRewardFromAccount, RewardsAccountOwner, RewardsAccountParams};
#	use sp_core::crypto::Ss58Codec;
#
#	// SS58=42
#	println!(
#		"ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_ThisChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32], LegacyLaneId>::rewards_account(RewardsAccountParams::new(
#				LegacyLaneId([0, 0, 0, 2]),
#				*b"bhwd",
#				RewardsAccountOwner::ThisChain
#			))
#		)
#			.to_ss58check_with_version(42_u16.into())
#	);
#	// SS58=42
#	println!(
#		"ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_BridgedChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32], LegacyLaneId>::rewards_account(RewardsAccountParams::new(
#				LegacyLaneId([0, 0, 0, 2]),
#				*b"bhwd",
#				RewardsAccountOwner::BridgedChain
#			))
#		)
#			.to_ss58check_with_version(42_u16.into())
#	);
#
#	// SS58=42
#	println!(
#		"ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_ThisChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32], LegacyLaneId>::rewards_account(RewardsAccountParams::new(
#				LegacyLaneId([0, 0, 0, 2]),
#				*b"bhro",
#				RewardsAccountOwner::ThisChain
#			))
#		)
#			.to_ss58check_with_version(42_u16.into())
#	);
#	// SS58=42
#	println!(
#		"ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_BridgedChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32], LegacyLaneId>::rewards_account(RewardsAccountParams::new(
#				LegacyLaneId([0, 0, 0, 2]),
#				*b"bhro",
#				RewardsAccountOwner::BridgedChain
#			))
#		)
#			.to_ss58check_with_version(42_u16.into())
#	);
#}
ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_ThisChain="5EHnXaT5GApse1euZWj9hycMbgjKBCNQL9WEwScL8QDx6mhK"
ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_BridgedChain="5EHnXaT5Tnt4A8aiP9CsuAFRhKPjKZJXRrj4a3mtihFvKpTi"
ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_ThisChain="5EHnXaT5GApry9tS6yd1FVusPq8o8bQJGCKyvXTFCoEKk5Z9"
ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_BridgedChain="5EHnXaT5Tnt3VGpEvc6jSgYwVToDGxLRMuYoZ8coo6GHyWbR"

LANE_ID="00000002"
XCM_VERSION=5
# 6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e
ROCOCO_GENESIS_HASH=[100,8,222,119,55,197,156,35,136,144,83,58,242,88,150,162,194,6,8,216,179,128,187,1,2,154,203,57,39,129,6,62]
# e143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e
WESTEND_GENESIS_HASH=[225,67,242,56,3,172,80,232,246,248,230,38,149,209,206,158,78,29,104,170,54,193,205,44,253,21,52,2,19,243,66,62]

function init_ro_wnd() {
    local relayer_path=$(ensure_relayer)

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path init-bridge rococo-to-bridge-hub-westend \
        --source-uri ws://localhost:9942 \
        --source-version-mode Auto \
        --target-uri ws://localhost:8945  \
        --target-version-mode Auto \
        --target-signer //Bob
}

function init_wnd_ro() {
    local relayer_path=$(ensure_relayer)

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path init-bridge westend-to-bridge-hub-rococo \
        --source-uri ws://localhost:9945  \
        --source-version-mode Auto \
        --target-uri ws://localhost:8943 \
        --target-version-mode Auto \
        --target-signer //Bob
}

function run_finality_relay() {
    local relayer_path=$(ensure_relayer)

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-headers rococo-to-bridge-hub-westend \
        --only-free-headers \
        --source-uri ws://localhost:9942 \
        --source-version-mode Auto \
        --target-uri ws://localhost:8945 \
        --target-version-mode Auto \
        --target-signer //Charlie \
        --target-transactions-mortality 4&

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-headers westend-to-bridge-hub-rococo \
        --only-free-headers \
        --source-uri ws://localhost:9945 \
        --source-version-mode Auto \
        --target-uri ws://localhost:8943 \
        --target-version-mode Auto \
        --target-signer //Charlie \
        --target-transactions-mortality 4
}

function run_parachains_relay() {
    local relayer_path=$(ensure_relayer)

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-parachains bridge-hub-rococo-to-bridge-hub-westend \
        --only-free-headers \
        --source-uri ws://localhost:9942 \
        --source-version-mode Auto \
        --target-uri ws://localhost:8945 \
        --target-version-mode Auto \
        --target-signer //Dave \
        --target-transactions-mortality 4&

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-parachains bridge-hub-westend-to-bridge-hub-rococo \
        --only-free-headers \
        --source-uri ws://localhost:9945 \
        --source-version-mode Auto \
        --target-uri ws://localhost:8943 \
        --target-version-mode Auto \
        --target-signer //Dave \
        --target-transactions-mortality 4
}

function run_messages_relay() {
    local relayer_path=$(ensure_relayer)

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-messages bridge-hub-rococo-to-bridge-hub-westend \
        --source-uri ws://localhost:8943 \
        --source-version-mode Auto \
        --source-signer //Eve \
        --source-transactions-mortality 4 \
        --target-uri ws://localhost:8945 \
        --target-version-mode Auto \
        --target-signer //Eve \
        --target-transactions-mortality 4 \
        --lane $LANE_ID&

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-messages bridge-hub-westend-to-bridge-hub-rococo \
        --source-uri ws://localhost:8945 \
        --source-version-mode Auto \
        --source-signer //Ferdie \
        --source-transactions-mortality 4 \
        --target-uri ws://localhost:8943 \
        --target-version-mode Auto \
        --target-signer //Ferdie \
        --target-transactions-mortality 4 \
        --lane $LANE_ID
}

case "$1" in
  run-finality-relay)
    init_wnd_ro
    init_ro_wnd
    run_finality_relay
    ;;
  run-parachains-relay)
    run_parachains_relay
    ;;
  run-messages-relay)
    run_messages_relay
    ;;
  init-rococo-local)
      # HRMP
      open_hrmp_channels \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1000 1013 4 524288
      open_hrmp_channels \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1013 1000 4 524288
      # governance set XCM version of remote AssetHubWestend on AHR
      force_xcm_version \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1000 \
          "ws://127.0.0.1:9910" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1000 } ] } }')" \
          $XCM_VERSION
      # governance set XCM version of remote BridgeHubWestend on BHR
      force_xcm_version \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1013 \
          "ws://127.0.0.1:8943" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1002 } ] } }')" \
          $XCM_VERSION
      ;;
  init-asset-hub-rococo-local)
      ensure_polkadot_js_api
      # create foreign asset pool
      create_pool \
          "ws://127.0.0.1:9910" \
          "//Bob" \
          "$(jq --null-input '{ "parents": 1, "interior": "Here" }')" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }] } }')"
      # Create liquidity in the pool
      add_liquidity \
          "ws://127.0.0.1:9910" \
          "//Bob" \
          "$(jq --null-input '{ "parents": 1, "interior": "Here" }')" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }] } }')" \
          1000000000000 \
          2500000000000 \
          "$BOB_ACCOUNT_AT_ROCOCO"
      ;;
  init-bridge-hub-rococo-local)
      ensure_polkadot_js_api
      # SA of sibling asset hub pays for the execution
      transfer_balance \
          "ws://127.0.0.1:8943" \
          "//Alice" \
          "$ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO" \
          100000000000000
      # drip SA of lane dedicated to asset hub for paying rewards for delivery
      transfer_balance \
          "ws://127.0.0.1:8943" \
          "//Alice" \
          "$ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_ThisChain" \
          100000000000000
      # drip SA of lane dedicated to asset hub for paying rewards for delivery confirmation
      transfer_balance \
          "ws://127.0.0.1:8943" \
          "//Alice" \
          "$ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_BridgedChain" \
          100000000000000
      ;;
  init-westend-local)
      # HRMP
      open_hrmp_channels \
          "ws://127.0.0.1:9945" \
          "//Alice" \
          1000 1002 4 524288
      open_hrmp_channels \
          "ws://127.0.0.1:9945" \
          "//Alice" \
          1002 1000 4 524288
      # governance set XCM version of remote AssetHubRococo on AHW
      force_xcm_version \
          "ws://127.0.0.1:9945" \
          "//Alice" \
          1000 \
          "ws://127.0.0.1:9010" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1000 } ] } }')" \
          $XCM_VERSION
      # governance set XCM version of remote BridgeHubRococo on BHW
      force_xcm_version \
          "ws://127.0.0.1:9945" \
          "//Alice" \
          1002 \
          "ws://127.0.0.1:8945" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1013 } ] } }')" \
          $XCM_VERSION
      ;;
  init-asset-hub-westend-local)
      ensure_polkadot_js_api
      # create foreign asset pool
      create_pool \
          "ws://127.0.0.1:9010" \
          "//Bob" \
          "$(jq --null-input '{ "parents": 1, "interior": "Here" }')" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }] } }')"
      # Create liquidity in the pool
      add_liquidity \
          "ws://127.0.0.1:9010" \
          "//Bob" \
          "$(jq --null-input '{ "parents": 1, "interior": "Here" }')" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }] } }')" \
          1000000000000 \
          4000000000000 \
          "$BOB_ACCOUNT_AT_WESTEND"
      ;;
  init-bridge-hub-westend-local)
      # SA of sibling asset hub pays for the execution
      transfer_balance \
          "ws://127.0.0.1:8945" \
          "//Alice" \
          "$ASSET_HUB_WESTEND_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WESTEND" \
          100000000000000
      # drip SA of lane dedicated to asset hub for paying rewards for delivery
      transfer_balance \
          "ws://127.0.0.1:8945" \
          "//Alice" \
          "$ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_ThisChain" \
          100000000000000
      # drip SA of lane dedicated to asset hub for paying rewards for delivery confirmation
      transfer_balance \
          "ws://127.0.0.1:8945" \
          "//Alice" \
          "$ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_BridgedChain" \
          100000000000000
      ;;
  reserve-transfer-assets-from-asset-hub-rococo-local)
      amount=$2
      ensure_polkadot_js_api
      # send ROCs to Alice account on AHW
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9910" \
          "//Alice" \
          "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \
          "$(jq --null-input '{ "V5": [ { "id": { "parents": 1, "interior": "Here" }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  withdraw-reserve-assets-from-asset-hub-rococo-local)
      amount=$2
      ensure_polkadot_js_api
      # send back only 100000000000 wrappedWNDs to Alice account on AHW
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9910" \
          "//Alice" \
          "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \
          "$(jq --null-input '{ "V5": [ { "id": { "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }] } }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  reserve-transfer-assets-from-asset-hub-westend-local)
      amount=$2
      ensure_polkadot_js_api
      # send WNDs to Alice account on AHR
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9010" \
          "//Alice" \
          "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \
          "$(jq --null-input '{ "V5": [ { "id": { "parents": 1, "interior": "Here" }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  withdraw-reserve-assets-from-asset-hub-westend-local)
      amount=$2
      ensure_polkadot_js_api
      # send back only 100000000000 wrappedROCs to Alice account on AHR
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9010" \
          "//Alice" \
          "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \
          "$(jq --null-input '{ "V5": [ { "id": { "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }] } }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  claim-rewards-bridge-hub-rococo-local)
      ensure_polkadot_js_api
      # bhwd -> [62, 68, 77, 64] -> 0x62687764
      claim_rewards \
          "ws://127.0.0.1:8943" \
          "//Charlie" \
          "0x${LANE_ID}" \
          "0x62687764" \
          "ThisChain"
      claim_rewards \
          "ws://127.0.0.1:8943" \
          "//Charlie" \
          "0x${LANE_ID}" \
          "0x62687764" \
          "BridgedChain"
      ;;
  claim-rewards-bridge-hub-westend-local)
      # bhro -> [62, 68, 72, 6f] -> 0x6268726f
      claim_rewards \
          "ws://127.0.0.1:8945" \
          "//Charlie" \
          "0x${LANE_ID}" \
          "0x6268726f" \
          "ThisChain"
      claim_rewards \
          "ws://127.0.0.1:8945" \
          "//Charlie" \
          "0x${LANE_ID}" \
          "0x6268726f" \
          "BridgedChain"
      ;;
  stop)
    pkill -f polkadot
    pkill -f parachain
    ;;
  import)
    # to avoid trigger anything here
    ;;
  *)
    echo "A command is require. Supported commands for:
    Local (zombienet) run:
          - run-finality-relay
          - run-parachains-relay
          - run-messages-relay
          - init-rococo-local
          - init-asset-hub-rococo-local
          - init-bridge-hub-rococo-local
          - init-westend-local
          - init-asset-hub-westend-local
          - init-bridge-hub-westend-local
          - reserve-transfer-assets-from-asset-hub-rococo-local
          - withdraw-reserve-assets-from-asset-hub-rococo-local
          - reserve-transfer-assets-from-asset-hub-westend-local
          - withdraw-reserve-assets-from-asset-hub-westend-local
          - claim-rewards-bridge-hub-rococo-local
          - claim-rewards-bridge-hub-westend-local";
    exit 1
    ;;
esac
