#!/bin/bash

# Holders 服务启动脚本

echo "=== Starting Holders Services ==="

# 检查环境变量
if [ -z "$DB_PASSWORD" ]; then
    echo "⚠️  Warning: DB_PASSWORD not set, using default"
    export DB_PASSWORD="your_password"
fi

# 设置默认环境变量
export DB_TYPE=${DB_TYPE:-mysql}
export DB_HOST=${DB_HOST:-localhost}
export DB_PORT=${DB_PORT:-3306}
export DB_USER=${DB_USER:-root}
export DB_NAME=${DB_NAME:-assetx}
export GIN_MODE=${GIN_MODE:-release}
export PORT=${PORT:-8080}
export RPC_URL=${RPC_URL:-https://api.zan.top/node/v1/arb/sepolia/baf84c429d284bb5b676cb8c9ca21c07}

echo "Configuration:"
echo "  DB: $DB_TYPE://$DB_USER@$DB_HOST:$DB_PORT/$DB_NAME"
echo "  API Port: $PORT"
echo "  RPC: ${RPC_URL:0:50}..."
echo ""

# 创建 bin 目录
mkdir -p bin

# 编译服务
echo "📦 Building services..."
go build -o bin/api-server main.go
go build -o bin/holder-scanner cmd/scanner/main.go
echo "✓ Build completed"
echo ""

# 选择启动方式
echo "Choose start method:"
echo "1. API Server only"
echo "2. Scanner only"
echo "3. Both (in background)"
read -p "Enter choice [1-3]: " choice

case $choice in
    1)
        echo "🚀 Starting API Server..."
        ./bin/api-server
        ;;
    2)
        echo "🚀 Starting Scanner..."
        ./bin/holder-scanner
        ;;
    3)
        echo "🚀 Starting both services in background..."
        nohup ./bin/api-server > logs/api-server.log 2>&1 &
        API_PID=$!
        echo "  API Server started (PID: $API_PID)"

        nohup ./bin/holder-scanner > logs/holder-scanner.log 2>&1 &
        SCANNER_PID=$!
        echo "  Scanner started (PID: $SCANNER_PID)"

        echo ""
        echo "Services running:"
        echo "  API: http://localhost:$PORT"
        echo "  Logs: tail -f logs/api-server.log"
        echo "        tail -f logs/holder-scanner.log"
        echo ""
        echo "To stop:"
        echo "  kill $API_PID $SCANNER_PID"
        ;;
    *)
        echo "Invalid choice"
        exit 1
        ;;
esac
