#!/bin/bash

# 获取当前脚本所在目录路径
work_dir=$(dirname $(readlink -f "$0"))

# 字义install.log文件路径
log_file="$work_dir/install.log"

# 定义deploy目录路径
deploy_dir="$work_dir/deploy"

# 定时清理脚本
cleaner_script="auto_cleaner.sh"

# 编译脚本
build_script="auto_build.sh"

# 定时任务命令
cron_command="sh $work_dir/$cleaner_script $work_dir/"

# 检查install.lock文件是否存在
if [ -f "$work_dir/install.lock" ]; then
    install_time=$(cat "$work_dir/install.lock")
    echo "项目已在$install_time完成安装,如需重新安装,可以手动删除install.lock文件后再尝试执行安装脚本"
    exit 1
fi

# 创建install.lock文件
current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "$current_time" >"$work_dir/install.lock"

# 检查.env文件是否存在
env_file="$deploy_dir/.env"
if [ -f "$env_file" ]; then
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] .env文件已存在,跳过创建" >>"$log_file"
else
    # 创建.env文件
    branch=$(git branch --show-current)
    git_url=$(git remote -v | grep fetch | awk '{print $2}')
    echo "WORK_DIR = \"$work_dir\"" >"$env_file"
    echo "BRANCH = \"$branch\"" >>"$env_file"
    echo "GIT_URL = \"$git_url\"" >>"$env_file"
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] .env文件创建成功" >>"$log_file"
fi

# 进入deploy目录
cd "$deploy_dir"

start_script="start.php"
# 先尝试停止一次应用
php "$start_script" stop
stop_result=$?
echo "[$(date +"%Y-%m-%d %H:%M:%S")] 先尝试执行php $start_script stop,结果:$stop_result" | tee -a "$log_file"

# 执行composer install
yes | composer install
install_result=$?
if [ $install_result -ne 0 ]; then
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] PHP环境可能异常,自动拉新功能很可能不会生效" | tee -a "$log_file"
fi
echo "[$(date +"%Y-%m-%d %H:%M:%S")] 执行composer install,结果:$install_result" | tee -a "$log_file"

# 启动应用
if [ -f "$start_script" ]; then
    php "$start_script" start -d
    start_result=$?
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] 执行php $start_script start -d,结果:$start_result" | tee -a "$log_file"
    if [ $start_result -ne 0 ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] PHP环境可能异常,自动拉新功能不会生效" | tee -a "$log_file"
    else
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] deploy服务启动成功" | tee -a "$log_file"
    fi
else
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] start.php文件不存在,代码不完整,自动拉新功能不会生效" | tee -a "$log_file"
fi

# 退出deploy目录
cd ..

# 检查auto_cleaner.sh文件和定时任务
auto_cleaner_script="$work_dir/auto_cleaner.sh"
if [ ! -f "$auto_cleaner_script" ]; then
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] 未找到$auto_cleaner_script文件,跳过" | tee -a "$log_file"
else
    existing_cron=$(crontab -l | grep -F "$cron_command")
    if [ -n "$existing_cron" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] auto_cleaner.sh任务已存在,跳过" | tee -a "$log_file"
    else
        (
            crontab -l 2>/dev/null
            echo "*/10 * * * * $cron_command"
        ) | crontab -
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] auto_cleaner.sh任务安装成功" | tee -a "$log_file"
    fi
fi

# 执行编译脚本
sh $build_script

echo "[$(date +"%Y-%m-%d %H:%M:%S")] 安装完毕,在$log_file中可以查看完整的安装日志" | tee -a "$log_file"

# 退出
exit 0