#!/bin/bash

set -eo pipefail

function usage() {
cat <<EOF >&2
Usage:

  $(basename "$0") <devnet|testnet|mainnet> -- Deploy the contracts
EOF
exit 1
}

# cd to script directory so that we can run this script from anywhere
cd "$(dirname "$0")"
NETWORK=$1 || usage

if [ "$NETWORK" = mainnet ]; then
    GUARDIAN_ADDR=0x58CC3AE5C097b213cE3c81979e1B9f9570746AA5

elif [ "$NETWORK" = testnet ]; then
    GUARDIAN_ADDR=0x13947Bd48b18E53fdAeEe77F3473391aC727C638

elif [ "$NETWORK" = devnet ]; then
    DOTENV=$(dirname $0)/../.env
    [[ -f "$DOTENV" ]] && . "$DOTENV"

    GUARDIAN_ADDR="${INIT_SIGNERS_CSV:-0xbeFA429d57cD18b7F8A4d91A2da9AB4AF05d0FBe}"

    worm aptos faucet
else
    usage
fi

NAMED_ADDRS="wormhole=$WORMHOLE_ADDR,deployer=$DEPLOYER_ADDR,token_bridge=$TOKEN_BRIDGE_ADDR"
NAMED_ADDRS="$(./named_addresses $NETWORK)"

echo "Addresses: $NAMED_ADDRS"

# NOTE: this always succeeds, even if the deployer contact is already deployed
echo "[1/6] Deploying deployer contract for creating resource accounts..."
worm aptos deploy --network "$NETWORK" ../deployer --named-addresses "$NAMED_ADDRS"

echo "[2/6] Deploying wormhole contract..."
worm aptos deploy-resource wormhole --network "$NETWORK" ../wormhole --named-addresses "$NAMED_ADDRS"

echo "[3/6] Initialising wormhole with guardian(s) $GUARDIAN_ADDR..."
worm aptos init-wormhole --network "$NETWORK" -g $GUARDIAN_ADDR

echo "[4/6] Deploying token bridge contract..."
worm aptos deploy-resource token_bridge --network "$NETWORK" ../token_bridge --named-addresses "$NAMED_ADDRS"

echo "[5/6] Initialising token bridge..."
worm aptos init-token-bridge --network "$NETWORK"

echo "[6/6] Deploying (& initialising) NFT bridge contract..."
worm aptos deploy-resource nft_bridge --network "$NETWORK" ../nft_bridge --named-addresses "$NAMED_ADDRS"

if [ "$NETWORK" = devnet ]; then
    echo "[+1] Deploying example contract..."
    worm aptos deploy --network "$NETWORK" ../examples/core_messages --named-addresses "$NAMED_ADDRS"
fi

echo "Deployments successful."
