#!/bin/bash
set -e

echo "============================================"
echo "  品居会 - 服务器首次初始化"
echo "============================================"
echo ""

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# ===== 1. 系统更新 =====
echo ">>> 更新系统包..."
sudo apt update && sudo apt upgrade -y

# ===== 2. 安装 Docker =====
if ! command -v docker &> /dev/null; then
    echo ">>> 安装 Docker..."
    curl -fsSL https://get.docker.com | sh
    sudo usermod -aG docker $USER
    echo "Docker 已安装。可能需要重新登录以生效。"
else
    echo ">>> Docker 已安装，跳过。"
fi

# ===== 3. 验证 Docker Compose =====
if ! docker compose version &> /dev/null; then
    echo ">>> 安装 Docker Compose 插件..."
    sudo apt install -y docker-compose-plugin
else
    echo ">>> Docker Compose 已安装，跳过。"
fi

# ===== 4. 安装 Git =====
if ! command -v git &> /dev/null; then
    echo ">>> 安装 Git..."
    sudo apt install -y git
else
    echo ">>> Git 已安装，跳过。"
fi

# ===== 5. 安装 pnpm =====
if ! command -v pnpm &> /dev/null; then
    echo ">>> 安装 pnpm..."
    npm install -g pnpm 2>/dev/null || { echo "需要先安装 Node.js"; exit 1; }
else
    echo ">>> pnpm 已安装，跳过。"
fi

# ===== 6. 配置环境变量 =====
ENV_FILE="$PROJECT_DIR/deploy/docker/.env"

if [ ! -f "$ENV_FILE" ]; then
    echo ">>> 创建 .env 文件..."
    cp "$PROJECT_DIR/deploy/docker/.env.example" "$ENV_FILE"
    echo ""
    echo "    *** 重要 ***"
    echo "    请编辑 $ENV_FILE 填入真实密码和密钥。"
    echo "    必填变量："
    echo "      - PROD_DB_PASSWORD    生产环境数据库密码"
    echo "      - PROD_JWT_SECRET     生产环境 JWT 密钥"
    echo "      - TEST_DB_PASSWORD    测试环境数据库密码"
    echo "      - TEST_JWT_SECRET     测试环境 JWT 密钥"
    echo ""
    read -p "    按 Enter 打开编辑器，或 Ctrl+C 退出手动编辑..."
    ${EDITOR:-vi} "$ENV_FILE"
else
    echo ">>> .env 文件已存在，跳过。"
fi

# ===== 7. 创建 Docker 网络 =====
echo ">>> 创建 Docker 网络..."
docker network create rent-prod 2>/dev/null || echo "  rent-prod 网络已存在。"
docker network create rent-test 2>/dev/null || echo "  rent-test 网络已存在。"

# ===== 8. 启动 Gitea =====
echo ">>> 启动 Gitea + Act Runner..."
cd "$PROJECT_DIR"
docker compose -f deploy/docker/docker-compose.gitea.yml up -d

echo ""
echo "    等待 Gitea 启动（约 30 秒）..."
sleep 30

# ===== 9. 启动 Gateway =====
echo ">>> 启动 Gateway Nginx..."
docker compose -f deploy/docker/docker-compose.gateway.yml up -d

echo ""
echo "============================================"
echo "  初始化完成！"
echo "============================================"
echo ""
echo "后续步骤："
echo ""
echo "  1. 配置 Gitea："
echo "     访问 http://服务器IP:3002 完成初始设置"
echo "     创建管理员账号，创建仓库"
echo ""
echo "  2. 注册 Act Runner："
echo "     Gitea → Settings → Actions → Runners → Create Runner"
echo "     复制 Registration Token"
echo "     编辑 $PROJECT_DIR/deploy/docker/.env"
echo "     将 GITEA_RUNNER_TOKEN 替换为真实 token"
echo "     然后重启：docker compose -f deploy/docker/docker-compose.gitea.yml restart act-runner"
echo ""
echo "  3. 推送代码到 Gitea："
echo "     git remote add gitea http://服务器IP:3002/用户名/rent-platform.git"
echo "     git push gitea master"
echo "     git push gitea test"
echo ""
echo "  4. 部署服务："
echo "     make prod-deploy    # 生产环境"
echo "     make test-deploy     # 测试环境"
echo ""
echo "  5. 配置 DNS 记录指向本服务器 IP："
echo "     生产：api/www/merchant/platform-admin.pinzhuhui.com"
echo "     测试：api-test/test/merchant-test/platform-admin-test.pinzhuhui.com"
echo ""
