#!/bin/bash

set -euo pipefail

if [ $# == 0 ]
  then
    chain=ethereum
else
    chain=$1
fi

# Run the upgrade simulation (./simulate_upgrade) against each contract twice
# against the ethereum mainnet state. Running the upgrade twice ensures that the
# contract is still upgradeable after the first upgrade.

ANVIL_PID=""
function clean_up () {
    ARG=$?
    [ -n "$ANVIL_PID" ] && kill "$ANVIL_PID"
    exit $ARG
}
trap clean_up SIGINT SIGTERM EXIT

echo "🍴 Forking mainnet for $chain ..."
./anvil_fork $chain > /dev/null &
ANVIL_PID=$!

# Sleep for 10 seconds here to give some time for the fork to complete.
sleep 10

echo "========================= Updating core contract ============================"
./simulate_upgrade -m bridge -c $chain -d
echo "========================= Shutting down core contract ======================="
./simulate_upgrade -m bridge -c $chain -d -s
echo "========================= Re-enabling core contract ========================="
./simulate_upgrade -m bridge -c $chain -d

echo "===================== Updating token bridge contract ========================"
./simulate_upgrade -m token_bridge -c $chain -d
echo "===================== Shutting down token bridge contract ==================="
./simulate_upgrade -m token_bridge -c $chain -d -s
echo "===================== Re-enabling token bridge contract ====================="
./simulate_upgrade -m token_bridge -c $chain -d

echo "====================== Updating NFT bridge contract ========================="
./simulate_upgrade -m nft_bridge -c $chain -d
echo "====================== Shutting down NFT bridge contract ===================="
./simulate_upgrade -m nft_bridge -c $chain -d -s
echo "====================== Re-enabling NFT bridge contract ======================"
./simulate_upgrade -m nft_bridge -c $chain -d
