#!/bin/bash

set -euo pipefail


if [[ "${UPGRADE_DAEMONIZED:-0}" != "1" ]]; then
  export UPGRADE_DAEMONIZED=1
  nohup "$0" "$@" >/dev/null 2>&1 &
  exit 0
fi

# ---------- 参数校验 ----------
if [ "$#" -ne 2 ]; then
  echo "用法: $0 <old_version> <new_version>"
  exit 1
fi

old_version="$1"
new_version="$2"

# ---------- 脚本目录 ----------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# ---------- 日志 ----------
LOG_DIR="${SCRIPT_DIR}/upgrade_logs"
LOG_FILE="${LOG_DIR}/upgrade_${old_version}_to_${new_version}.log"
mkdir -p "$LOG_DIR"

# 覆盖写日志（重要）
: > "$LOG_FILE"

# 所有输出写日志 + 控制台
exec > >(tee -a "$LOG_FILE") 2>&1

echo "===== Upgrade start: $(date) ====="
echo "old_version=${old_version}"
echo "new_version=${new_version}"
echo "SCRIPT_DIR=${SCRIPT_DIR}"

# ---------- 路径定义 ----------
OLD_DIR="${SCRIPT_DIR}/${old_version}"
NEW_DIR="${SCRIPT_DIR}/${new_version}"
PKG="${NEW_DIR}/${new_version}.zip"
STOP_SCRIPT="${OLD_DIR}/stop.bash"
PT_BIN="${NEW_DIR}/pt"
PROTECT_SCRIPT="${SCRIPT_DIR}/protect.bash"

# ---------- 基础校验 ----------
for d in "$OLD_DIR" "$NEW_DIR"; do
  [ -d "$d" ] || { echo "目录不存在: $d"; exit 1; }
done

[ -f "$PKG" ] || { echo "升级包不存在: $PKG"; exit 1; }

command -v unzip >/dev/null || { echo "unzip 未安装"; exit 1; }

# ---------- 停止旧版本 ----------
echo "[1/5] 停止旧版本"
if [ -x "$STOP_SCRIPT" ]; then
  "$STOP_SCRIPT"
else
  echo "stop.bash 不存在或不可执行: $STOP_SCRIPT"
  exit 1
fi

# ---------- 解压新版本（覆盖） ----------
echo "[2/5] 解压新版本"
unzip -o "$PKG" -d "$NEW_DIR"

# ---------- 校验新程序 ----------
echo "[3/5] 校验新程序"
[ -f "$PT_BIN" ] || { echo "pt 程序不存在: $PT_BIN"; exit 1; }
chmod +x "$PT_BIN"

# ---------- 写 protect.bash（覆盖） ----------
echo "[4/5] 写 protect.bash"

cat > "$PROTECT_SCRIPT" <<EOF
#!/bin/bash
set -e

NAME="ecap_server"
DIR="/home/heco/ys_ecap_server/${new_version}"

if [ ! -x "\${DIR}/pt" ]; then
    echo "pt 不存在或不可执行: \${DIR}/pt"
    exit 1
fi

"\${DIR}/pt" > "\${DIR}/pt.log" 2>&1
EOF

chmod +x "$PROTECT_SCRIPT"

# ---------- 启动新版本 ----------
echo "[5/5] 启动新版本"

LOG_FILE="${NEW_DIR}/pt.log"

# 确保日志文件存在
if [ ! -e "$LOG_FILE" ]; then
  touch "$LOG_FILE"
fi

# 设置日志权限
chmod 777 "$LOG_FILE"

# 后台启动新版本
nohup "$PT_BIN"  0 >> "$LOG_FILE" 2>&1 &
disown

echo "Upgrade finished, pt started in background"
exit 0