#!/usr/bin/env bash

set -e

# Deploy multi-sig wallet for admin operations
# For production, consider using Gnosis Safe instead

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

RPC_URL="${RPC_URL:-http://localhost:8545}"
PRIVATE_KEY="${PRIVATE_KEY:-}"
OWNERS="${OWNERS:-}"  # Comma-separated list of owner addresses

if [ -z "$PRIVATE_KEY" ]; then
    echo "Error: PRIVATE_KEY not set"
    exit 1
fi

if [ -z "$OWNERS" ]; then
    echo "Error: OWNERS not set (comma-separated list)"
    exit 1
fi

echo "Deploying Multi-Sig Wallet"
echo "RPC URL: $RPC_URL"
echo "Owners: $OWNERS"
echo "Required: $REQUIRED"

# Convert comma-separated owners to array format for Foundry
OWNERS_ARRAY=$(echo "$OWNERS" | tr ',' ' ')

# Deploy using Foundry
forge script "$PROJECT_ROOT/script/DeployMultiSig.s.sol:DeployMultiSig" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --verify

echo "Multi-sig wallet deployed successfully!"
echo "Next steps:"
echo "1. Transfer admin roles to multi-sig address"
echo "2. Test multi-sig operations"
echo "3. Document multi-sig procedures"

