#!/bin/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;
#
#	parameter_types! {
#		pub UniversalLocationAHP: InteriorLocation = [GlobalConsensus(Polkadot), Parachain(1000)].into();
#		pub UniversalLocationAHK: InteriorLocation = [GlobalConsensus(Kusama), Parachain(1000)].into();
#	}
#
#
#	println!(
#		"ASSET_HUB_KUSAMA_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_KUSAMA=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			SiblingParachainConvertsVia::<Sibling, [u8; 32]>::convert_location(&Location {
#				parents: 1,
#				interior: [Parachain(1000)].into()
#			})
#			.unwrap()
#		)
#		.to_ss58check_with_version(2_u16.into())
#	);
#
#
#	println!(
#		"ASSET_HUB_POLKADOT_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_POLKADOT=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			SiblingParachainConvertsVia::<Sibling, [u8; 32]>::convert_location(&Location {
#				parents: 1,
#				interior: [Parachain(1000)].into()
#			})
#			.unwrap()
#		)
#		.to_ss58check_with_version(0_u16.into())
#	);
#}
ASSET_HUB_KUSAMA_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_KUSAMA="FBeL7EFTDeHnuViqaUHUXvhhUusN5FawDmHgfvzF97DXFr3"
ASSET_HUB_POLKADOT_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_POLKADOT="13cKp89SgdtqUngo2WiEijPrQWdHFhzYZLf2TJePKRvExk7o"
BOB_SOVEREIGN_ACCOUNT_AT_KUSAMA="FoQJpPyadYccjavVdTWxpxU7rUEaYhfLCPwXgkfD6Zat9QP"
BOB_SOVEREIGN_ACCOUNT_AT_POLKADOT="14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3"

# Expected sovereign accounts for rewards on BridgeHubs.
#
# Generated by:
##[test]
#fn generate_sovereign_accounts_for_rewards() {
#	use bp_messages::LaneId;
#	use bp_relayers::{PayRewardFromAccount, RewardsAccountOwner, RewardsAccountParams};
#	use sp_core::crypto::Ss58Codec;
#
#	println!(
#		"ON_BRIDGE_HUB_POLKADOT_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhks_ThisChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32]>::rewards_account(RewardsAccountParams::new(
#				LaneId([0, 0, 0, 1]),
#				*b"bhks",
#				RewardsAccountOwner::ThisChain
#			))
#		)
#		.to_ss58check_with_version(0_u16.into())
#	);
#
#	println!(
#		"ON_BRIDGE_HUB_POLKADOT_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhks_BridgedChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32]>::rewards_account(RewardsAccountParams::new(
#				LaneId([0, 0, 0, 1]),
#				*b"bhks",
#				RewardsAccountOwner::BridgedChain
#			))
#		)
#		.to_ss58check_with_version(0_u16.into())
#	);
#
#
#	println!(
#		"ON_BRIDGE_HUB_KUSAMA_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhpd_ThisChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32]>::rewards_account(RewardsAccountParams::new(
#				LaneId([0, 0, 0, 1]),
#				*b"bhpd",
#				RewardsAccountOwner::ThisChain
#			))
#		)
#		.to_ss58check_with_version(2_u16.into())
#	);
#
#	println!(
#		"ON_BRIDGE_HUB_KUSAMA_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhpd_BridgedChain=\"{}\"",
#		frame_support::sp_runtime::AccountId32::new(
#			PayRewardFromAccount::<[u8; 32], [u8; 32]>::rewards_account(RewardsAccountParams::new(
#				LaneId([0, 0, 0, 1]),
#				*b"bhpd",
#				RewardsAccountOwner::BridgedChain
#			))
#		)
#		.to_ss58check_with_version(2_u16.into())
#	);
#}
ON_BRIDGE_HUB_POLKADOT_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhks_ThisChain="13E5fui93Uyua5RtDv2LQj4aVBBHo6YREe3n6CBwYdqNqoxj"
ON_BRIDGE_HUB_POLKADOT_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhks_BridgedChain="13E5fui93Uyua5RtDv2c9kcAbfrVFeeHyJzHe8sn1Ti77Afd"
ON_BRIDGE_HUB_KUSAMA_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhpd_ThisChain="EoQBtnwp4jMtCEpV7C88rKrz6x1qMBh2z74ibGSqtZRnuMM"
ON_BRIDGE_HUB_KUSAMA_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhpd_BridgedChain="EoQBtnwp4jMtCEpV7CPsssT6bdDHuHZmf3aGXxHJiSA4Dz3"

LANE_ID="00000001"
XCM_VERSION=5

DOT=10000000000

KSM=1000000000000

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

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

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

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

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

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-headers-and-messages bridge-hub-kusama-bridge-hub-polkadot \
        --polkadot-uri ws://localhost:9942 \
        --polkadot-version-mode Auto \
        --bridge-hub-polkadot-uri ws://localhost:8943 \
        --bridge-hub-polkadot-version-mode Auto \
        --bridge-hub-polkadot-signer //Charlie \
        --bridge-hub-polkadot-transactions-mortality 4 \
        --kusama-uri ws://localhost:9945 \
        --kusama-version-mode Auto \
        --bridge-hub-kusama-uri ws://localhost:8945 \
        --bridge-hub-kusama-version-mode Auto \
        --bridge-hub-kusama-signer //Charlie \
        --bridge-hub-kusama-transactions-mortality 4 \
        --lane "${LANE_ID}"
}

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

    RUST_LOG=runtime=trace,rpc=trace,bridge=trace \
        $relayer_path relay-headers polkadot-to-bridge-hub-kusama \
        --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 kusama-to-bridge-hub-polkadot \
        --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-polkadot-to-bridge-hub-kusama \
        --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-kusama-to-bridge-hub-polkadot \
        --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-polkadot-to-bridge-hub-kusama \
        --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-kusama-to-bridge-hub-polkadot \
        --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-relay)
    init_kusama_polkadot
    init_polkadot_kusama
    run_relay
    ;;
  run-finality-relay)
    init_kusama_polkadot
    init_polkadot_kusama
    run_finality_relay
    ;;
  run-parachains-relay)
    run_parachains_relay
    ;;
  run-messages-relay)
    run_messages_relay
    ;;
  init-polkadot-local)
      ensure_polkadot_js_api
      # HRMP
      open_hrmp_channels \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1000 1002 4 524288
      open_hrmp_channels \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1002 1000 4 524288
      # governance set XCM version of remote AssetHubKusama on AHP
      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": "Kusama" }, { "Parachain": 1000 } ] } }')" \
          $XCM_VERSION
      # governance set XCM version of remote BridgeHubKusama on BHP
      force_xcm_version \
          "ws://127.0.0.1:9942" \
          "//Alice" \
          1002 \
          "ws://127.0.0.1:8943" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Kusama" }, { "Parachain": 1002 } ] } }')" \
          $XCM_VERSION
      ;;
  init-asset-hub-polkadot-local)
      ensure_polkadot_js_api
      # create pool for DOT and wKSM
      create_pool \
          "ws://127.0.0.1:9910" \
          "//Bob" \
          "$(jq --null-input '{ "parents": 1, "interior": "Here" }')" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": "Kusama" }] } }')"
      # 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": "Kusama"}] } }')" \
          100000000000 \
          4000000000000 \
          "$BOB_SOVEREIGN_ACCOUNT_AT_POLKADOT"
      ;;
  init-bridge-hub-polkadot-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_POLKADOT_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_POLKADOT" \
          $((25 * $DOT))
      # 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_POLKADOT_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhks_ThisChain" \
          $((25 * $DOT))
      # 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_POLKADOT_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhks_BridgedChain" \
          $((25 * $DOT))
      ;;
  init-kusama-local)
      ensure_polkadot_js_api
      # 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 AssetHubPolkadot on AHK
      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": "Polkadot" }, { "Parachain": 1000 } ] } }')" \
          $XCM_VERSION
      # governance set XCM version of remote BridgeHubPolkadot on BHK
      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": "Polkadot" }, { "Parachain": 1002 } ] } }')" \
          $XCM_VERSION
      ;;
  init-asset-hub-kusama-local)
      ensure_polkadot_js_api
      # create pool for KSM and wDOT
      create_pool \
          "ws://127.0.0.1:9010" \
          "//Bob" \
          "$(jq --null-input '{ "parents": 1, "interior": "Here" }')" \
          "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": "Polkadot" }] } }')"
      # 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": "Polkadot"}] } }')" \
          1000000000000 \
          25000000000 \
          "$BOB_SOVEREIGN_ACCOUNT_AT_KUSAMA"
      ;;
  init-bridge-hub-kusama-local)
      # SA of sibling asset hub pays for the execution
      transfer_balance \
          "ws://127.0.0.1:8945" \
          "//Alice" \
          "$ASSET_HUB_KUSAMA_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_KUSAMA" \
          $((25 * $KSM))
      # 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_KUSAMA_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhpd_ThisChain" \
          $((25 * $KSM))
      # 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_KUSAMA_SOVEREIGN_ACCOUNT_FOR_LANE_00000001_bhpd_BridgedChain" \
          $((25 * $KSM))
      ;;
  reserve-transfer-assets-from-asset-hub-polkadot-local)
      amount=$2
      ensure_polkadot_js_api
      # send DOTs to Alice account on AHK
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9910" \
          "//Alice" \
          "$(jq --null-input '{ "V4": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Kusama" }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V4": { "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 '{ "V4": [ { "id": { "parents": 1, "interior": "Here" }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  withdraw-reserve-assets-from-asset-hub-polkadot-local)
      amount=$2
      ensure_polkadot_js_api
      # send back some wrappedKSMs to Alice account on AHK
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9910" \
          "//Alice" \
          "$(jq --null-input '{ "V4": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Kusama" }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V4": { "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 '{ "V4": [ { "id": { "parents": 2, "interior": { "X1": [ { "GlobalConsensus": "Kusama" } ] } }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  reserve-transfer-assets-from-asset-hub-kusama-local)
      amount=$2
      ensure_polkadot_js_api
      # send KSMs to Alice account on AHP
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9010" \
          "//Alice" \
          "$(jq --null-input '{ "V4": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Polkadot" }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V4": { "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 '{ "V4": [ { "id": { "parents": 1, "interior": "Here" }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  withdraw-reserve-assets-from-asset-hub-kusama-local)
      amount=$2
      ensure_polkadot_js_api
      # send back some wrappedDOTs to Alice account on AHP
      limited_reserve_transfer_assets \
          "ws://127.0.0.1:9010" \
          "//Alice" \
          "$(jq --null-input '{ "V4": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Polkadot" }, { "Parachain": 1000 } ] } } }')" \
          "$(jq --null-input '{ "V4": { "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 '{ "V4": [ { "id": { "parents": 2, "interior": { "X1": [ { "GlobalConsensus": "Polkadot" } ] } }, "fun": { "Fungible": '$amount' } } ] }')" \
          0 \
          "Unlimited"
      ;;
  *)
    echo "A command is require. Supported commands for:
    Local (zombienet) run:
          - run-relay
          - run-finality-relay
          - run-parachains-relay
          - run-messages-relay
          - init-asset-hub-polkadot-local
          - init-bridge-hub-polkadot-local
          - init-asset-hub-kusama-local
          - init-bridge-hub-kusama-local
          - reserve-transfer-assets-from-asset-hub-polkadot-local
          - withdraw-reserve-assets-from-asset-hub-polkadot-local
          - reserve-transfer-assets-from-asset-hub-kusama-local
          - withdraw-reserve-assets-from-asset-hub-kusama-local";
    exit 1
    ;;
esac
