# ============================================================
# Genex Contracts — Foundry 部署镜像
#
# 用于通过 Foundry 将合约部署到 Genex Chain
#
# 构建: docker build -t genex-contracts:latest .
# 部署: docker run -e RPC_URL=http://localhost:8545 \
#        -e DEPLOYER_PRIVATE_KEY=0x... \
#        -e USDC_ADDRESS=0x... \
#        genex-contracts:latest
# ============================================================

FROM ghcr.io/foundry-rs/foundry:latest

WORKDIR /contracts

# 复制项目文件
COPY foundry.toml remappings.txt ./
COPY lib/ ./lib/
COPY src/ ./src/
COPY script/ ./script/
COPY test/ ./test/

# 编译合约
RUN forge build

# 部署脚本
COPY <<'DEPLOY_SCRIPT' /deploy.sh
#!/bin/bash
set -euo pipefail

echo "============================================"
echo "  Genex Contracts — Deployment"
echo "============================================"

RPC_URL="${RPC_URL:-http://localhost:8545}"
echo "RPC: $RPC_URL"

# 等待链节点就绪
echo "Waiting for chain node..."
for i in $(seq 1 30); do
    if cast chain-id --rpc-url "$RPC_URL" 2>/dev/null; then
        echo "Chain node is ready!"
        break
    fi
    echo "  Attempt $i/30..."
    sleep 2
done

# 运行测试确认合约正确
echo ""
echo "Running contract tests..."
forge test --no-match-test "testFuzz" -v

# 部署
echo ""
echo "Deploying contracts..."
forge script script/Deploy.s.sol \
    --rpc-url "$RPC_URL" \
    --broadcast \
    -vvv

echo ""
echo "============================================"
echo "  Deployment Complete!"
echo "============================================"
DEPLOY_SCRIPT

RUN chmod +x /deploy.sh

ENTRYPOINT ["/deploy.sh"]
