#!/bin/bash
# Task #7 一键部署：
#   - 前端 build + rsync 到服务器
#   - 后端代码 rsync（排除 .env / data/ / uploads/）
#   - 确保服务器 .env 中存在 OUTPUTS_DIR=/home/aipro/outputs
#   - 在服务器创建 /home/aipro/outputs 目录
#   - npm install + pm2 restart
#   - curl 自检
#
# 用法：
#   DEPLOY_PASS='xxxx' bash deploy/deploy-task7.sh
#   或交互输入：
#   bash deploy/deploy-task7.sh

set -e

cd "$(dirname "$0")/.."

SERVER_IP="47.76.173.254"
SERVER_USER="root"
APP_DIR="/home/aipro/app"
PM2_NAME="aipro"
OUTPUTS_DIR_REMOTE="/home/aipro/outputs"

if [ -z "$DEPLOY_PASS" ]; then
  echo -n "请输入服务器密码: "
  read -s DEPLOY_PASS
  echo ""
fi
if [ -z "$DEPLOY_PASS" ]; then
  echo "错误: 密码不能为空"
  exit 1
fi

do_rsync() {
  local src="$1"
  local dest="$2"
  shift 2
  local extra_args="$@"
  /usr/bin/expect <<EOF
set timeout 600
spawn rsync -az --delete $extra_args "$src" "${SERVER_USER}@${SERVER_IP}:${dest}"
expect {
  "yes/no" { send "yes\r"; exp_continue }
  "password:" { send "${DEPLOY_PASS}\r" }
}
expect eof
catch wait result
exit [lindex \$result 3]
EOF
}

do_ssh() {
  local cmd="$1"
  /usr/bin/expect <<EOF
set timeout 300
spawn ssh -o StrictHostKeyChecking=no "${SERVER_USER}@${SERVER_IP}" "$cmd"
expect {
  "yes/no" { send "yes\r"; exp_continue }
  "password:" { send "${DEPLOY_PASS}\r" }
}
expect eof
catch wait result
exit [lindex \$result 3]
EOF
}

echo "========== [1/6] 构建前端 =========="
npm run build

echo "========== [2/6] 同步 dist/ =========="
do_rsync "dist/" "${APP_DIR}/dist/"

echo "========== [3/6] 同步后端（排除 node_modules/data/uploads/.env/outputs） =========="
do_rsync "cf-worker/" "${APP_DIR}/cf-worker/" "--exclude node_modules/ --exclude data/ --exclude uploads/ --exclude outputs/ --exclude .env"

echo "========== [4/6] 确保 OUTPUTS_DIR + 创建 outputs 目录 =========="
do_ssh "mkdir -p ${OUTPUTS_DIR_REMOTE} && chmod 755 ${OUTPUTS_DIR_REMOTE} && grep -q '^OUTPUTS_DIR=' ${APP_DIR}/cf-worker/.env || echo 'OUTPUTS_DIR=${OUTPUTS_DIR_REMOTE}' >> ${APP_DIR}/cf-worker/.env"

echo "========== [5/6] npm install + pm2 restart =========="
do_ssh "cd ${APP_DIR}/cf-worker && npm install --omit=dev && pm2 restart ${PM2_NAME} && pm2 save"

echo "========== [6/6] 健康检查 =========="
sleep 2
echo "-- /api/health --"
curl -fsS https://zhenyuskill.com/api/health || echo "(health 检查失败)"
echo ""
echo "-- /api/skill-run（无身份头，期望 401） --"
curl -s -o /dev/null -w "HTTP %{http_code}\n" https://zhenyuskill.com/api/skill-run
echo ""
echo "-- /api/skill-run/outputs/foo/bar.html（无身份头，期望 401） --"
curl -s -o /dev/null -w "HTTP %{http_code}\n" https://zhenyuskill.com/api/skill-run/outputs/foo/bar.html

echo ""
echo "✅ Task #7 部署完成"
