#!/usr/bin/env bash

if [ "$1" == "" ]; then
  echo tag required
  echo "$0" [tag]
fi

if [ "$TREZOR" != "" ]; then
  WALLET_OPTS="--trezor --mnemonic-indexes $TREZOR"
else
  PRIVKEY=${PRIVATE_KEY:='0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80'}
  WALLET_OPTS="--private-key $PRIVKEY"
fi

TAG=$1
RPC=${RPC_URL:-http://localhost:8545}
CHAINID=$(cast chain-id --rpc-url "$RPC")

cpbroadcast() {
  CONTRACT=$1
  mkdir -p deployment/"$TAG"/broadcast/"$CONTRACT"/"$CHAINID"
  cp broadcast/"$CONTRACT"/"$CHAINID"/run-latest.json deployment/"$TAG"/broadcast/"$CONTRACT"/"$CHAINID"/run-latest.json
}

rm -rf out/ broadcast/ cache/
./bin/build || exit 1

rm -rf deployment/"$TAG"
mkdir -p deployment/"$TAG"
cp -r out deployment/"$TAG"/

# shellcheck disable=SC2086
forge script script/Deploy.sol -vvvv --fork-url "$RPC" --broadcast $WALLET_OPTS
cpbroadcast Deploy.sol

if [ "$2" == "mock" ]; then
  sleep 1
  # shellcheck disable=SC2086
  forge script script/DeployMock.sol -vvvv --fork-url "$RPC" --broadcast $WALLET_OPTS
  cpbroadcast DeployMock.sol
fi

if [ "$2" == "mirror" ]; then
  sleep 1
  # shellcheck disable=SC2086
  forge script script/DeployMock.sol -vvvv --fork-url "$RPC" --broadcast $WALLET_OPTS
  cpbroadcast DeployMock.sol
  sleep 1
  # shellcheck disable=SC2086
  forge script script/DeployMirror.sol -vvvv --fork-url "$RPC" --broadcast $WALLET_OPTS
  cpbroadcast DeployMirror.sol
fi
