#!/bin/bash
LOCK_FILE="/www/wwwroot/cdkey/runtime/webman_git_update.lock"

# 检查锁文件
if [ -e "$LOCK_FILE" ]; then
    echo "更新已在进行中，跳过本次请求"
    exit 0
fi

# 创建锁文件
touch "$LOCK_FILE"

# 确保退出时删除锁文件
trap 'rm -f "$LOCK_FILE"' EXIT
# 配置日志文件
LOG_FILE="/www/wwwroot/cdkey/runtime/log/git-update.log"

{
    current_time=$(date +"%Y-%m-%d %H:%M:%S")
    echo "=== 开始更新: ${current_time} ==="
    
    # 1. 设置环境
    export HOME=/root
    export PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
    
    # 2. 切换到项目目录
    cd /www/wwwroot/cdkey/ || {
        echo "错误：无法进入项目目录"
        exit 1
    }
    
    # 3. 设置Git凭证
    #git config --global credential.helper 'store --file=/home/youruser/.git-credentials'
    
    # 4. 从GitHub拉取最新代码
    echo "拉取最新代码..."
    git fetch origin wjb || {
        echo "错误：git fetch失败"
        exit 1
    }
    
    git reset --hard origin/wjb || {
        echo "错误：git reset失败"
        exit 1
    }
    
    # 5. 安装Composer依赖
    # echo "安装Composer依赖..."
    # composer install --no-dev --optimize-autoloader || {
    #     echo "错误：composer install失败"
    #     exit 1
    # }
    
    # 6. 重启Webman
    # echo "重启Webman服务..."
    # php ./server/webman stop || {
    #     echo "错误：重启Webman失败"
    #     exit 1
    # }
    
    # 7. 清理操作
    #echo "清理缓存..."
    #php ./server/webman cache:clear
    
    current_time=$(date +"%Y-%m-%d %H:%M:%S")
    echo "=== 更新完成: ${current_time} ==="
    echo ""
} > "$LOG_FILE" 2>&1