#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$REPO_ROOT"
fi

RPC_URL="${RPC_URL_138:-${CHAIN138_RPC:-http://192.168.11.211:8545}}"
PRIVATE_KEY="${PRIVATE_KEY:-}"
GAS_PRICE="${GAS_PRICE:-1000000000}"
EXECUTE="${EXECUTE:-0}"
ONLY_FAMILY="${GAS_FAMILY:-${1:-}}"

if [[ -z "$PRIVATE_KEY" ]]; then
  echo "PRIVATE_KEY is required" >&2
  exit 1
fi

cmd=(
  bash scripts/forge/scope.sh script tokens
  script/deploy/DeployGasCanonicalTokens.s.sol:DeployGasCanonicalTokens
  --rpc-url "$RPC_URL"
  --broadcast
  --private-key "$PRIVATE_KEY"
  --legacy
  --with-gas-price "$GAS_PRICE"
  -vvv
)

export FOUNDRY_PROFILE="${FOUNDRY_PROFILE:-chain138}"
if [[ -n "$ONLY_FAMILY" ]]; then
  export GAS_FAMILY="$ONLY_FAMILY"
fi

echo "Chain 138 gas-canonical deploy"
echo "  profile: $FOUNDRY_PROFILE"
echo "  rpc: $RPC_URL"
echo "  gas price: $GAS_PRICE"
echo "  family: ${GAS_FAMILY:-all}"

if [[ "$EXECUTE" != "1" ]]; then
  echo "Dry run only. Re-run with EXECUTE=1 to broadcast."
  printf '  %q' "${cmd[@]}"
  echo
  exit 0
fi

cd "$REPO_ROOT"
"${cmd[@]}"
