#!/bin/bash

# Gitea Webhook 部署脚本
# 用法：./deploy.sh <branch>

set -e

BRANCH=${1:-test}
PROJECT_DIR="/www/dk_project/dk_app/rent"
REPO_URL="https://gitea.pinzhuhui.com/xiaoquan/rent.git"

echo "========================================="
echo "开始部署 - 分支: $BRANCH"
echo "========================================="

# 1. 初始化或更新代码
if [ ! -d "$PROJECT_DIR" ]; then
    echo "首次克隆代码..."
    cd /www/dk_project/dk_app
    git clone $REPO_URL
    cd $PROJECT_DIR
else
    echo "更新代码..."
    cd $PROJECT_DIR
    git fetch origin
    git checkout $BRANCH
    git pull origin $BRANCH
fi

echo "✅ 代码更新完成"
echo "当前分支: $(git branch --show-current)"
echo "最新提交: $(git log -1 --oneline)"

# 2. 部署
cd $PROJECT_DIR/deploy/docker

if [ "$BRANCH" == "test" ]; then
    echo "========================================="
    echo "部署到测试环境"
    echo "========================================="

    # 从环境变量或密钥文件读取
    source /root/.env.test 2>/dev/null || true

    docker-compose -f docker-compose.test.yml down --remove-orphans
    docker-compose -f docker-compose.test.yml build --parallel
    docker-compose -f docker-compose.test.yml up -d
    docker image prune -f

    echo "等待服务启动..."
    sleep 10
    docker-compose -f docker-compose.test.yml ps

    echo "✅ 测试环境部署完成"

elif [ "$BRANCH" == "prod" ]; then
    echo "========================================="
    echo "部署到生产环境"
    echo "========================================="

    # 从环境变量或密钥文件读取
    source /root/.env.prod 2>/dev/null || true

    docker-compose -f docker-compose.prod.yml down --remove-orphans
    docker-compose -f docker-compose.prod.yml build --parallel
    docker-compose -f docker-compose.prod.yml up -d
    docker image prune -f

    echo "等待服务启动..."
    sleep 10
    docker-compose -f docker-compose.prod.yml ps

    echo "✅ 生产环境部署完成"
else
    echo "❌ 未知分支: $BRANCH"
    exit 1
fi

echo "========================================="
echo "部署完成！"
echo "========================================="
