#!/bin/bash

set -eo pipefail

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

  $(basename "$0") <devnet|testnet> <Core|TokenBridge> -- Perform a contract upgrade
EOF
exit 1
}

NETWORK=$1 || usage
MODULE=$2 || usage

if [ "$NETWORK" = testnet ]; then
    # This script upgrades the core bridge in local devnet by generating a
    # governance VAA and submitting it

    DEPLOYER_ADDR=0x0108bc32f7de18a5f6e1e7d6ee7aff9f5fc858d0d87ac0da94dd8d2a5d267d6b
    [ -z "$GUARDIAN_SECRET" ] && echo "GUARDIAN_SECRET unset" >&2 && exit 1

elif [ "$NETWORK" = devnet ]; then
    GUARDIAN_SECRET=cfb12303a19cde580bb4dd771639b0d26bc68353645571a8cff516ab2ee113a0
    DEPLOYER_ADDR=0x277fa055b6a73c42c0662d5236c65c864ccbf2d4abd21f174a30c8b786eab84b
else
    usage
fi

WORMHOLE_ADDR=$(worm contract "$NETWORK" aptos Core)
TOKEN_BRIDGE_ADDR=$(worm contract "$NETWORK" aptos TokenBridge)

NAMED_ADDRS="wormhole=$WORMHOLE_ADDR,deployer=$DEPLOYER_ADDR,token_bridge=$TOKEN_BRIDGE_ADDR"

case "$MODULE" in
    Core)
        DIR="../wormhole"
    ;;
    TokenBridge)
        DIR="../token_bridge"
    ;;
    *) echo "unsupported module $MODULE" >&2
       usage
       ;;
esac

HASH=$(worm aptos hash-contracts $DIR --named-addresses "$NAMED_ADDRS")
VAA=$(worm generate upgrade -c aptos -a "$HASH" -m "$MODULE" -g $GUARDIAN_SECRET)

echo "Submitting VAA: $VAA"

# TODO: --contract-address should not be neded after the sdk has these addresses
CONTRACT_ADDR=$(worm contract "$NETWORK" aptos "$MODULE")
worm submit --network "$NETWORK" "$VAA" --contract-address "$CONTRACT_ADDR"
worm aptos upgrade $DIR --network "$NETWORK" --contract-address "$CONTRACT_ADDR" --named-addresses "$NAMED_ADDRS"
worm aptos migrate --network "$NETWORK" --contract-address "$CONTRACT_ADDR"
