#!/bin/bash
# 用法：
#   DEPLOY_PASS=你的密码 bash deploy/push.sh [all|frontend|backend]
#   或直接运行，会提示输入密码：
#   bash deploy/push.sh frontend

set -e

# 切换到项目根目录
cd "$(dirname "$0")/.."

# 服务器信息
SERVER_IP="47.76.173.254"
SERVER_USER="root"
APP_DIR="/home/aipro/app"
PM2_NAME="aipro"

# 获取密码
if [ -z "$DEPLOY_PASS" ]; then
  echo -n "请输入服务器密码: "
  read -s DEPLOY_PASS
  echo ""
fi

if [ -z "$DEPLOY_PASS" ]; then
  echo "错误: 密码不能为空"
  exit 1
fi

# 部署模式
MODE="${1:-all}"

# expect 封装的 rsync
do_rsync() {
  local src="$1"
  local dest="$2"
  shift 2
  local extra_args="$@"

  /usr/bin/expect <<EOF
set timeout 300
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
}

# expect 封装的 ssh
do_ssh() {
  local cmd="$1"

  /usr/bin/expect <<EOF
set timeout 120
spawn ssh "${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
}

# 部署前端
deploy_frontend() {
  echo "========== 部署前端 =========="

  echo ">> 构建前端..."
  npm run build

  echo ">> 同步 dist/ 到服务器..."
  do_rsync "dist/" "${APP_DIR}/dist/"

  echo ">> 前端部署完成"
}

# 部署后端
deploy_backend() {
  echo "========== 部署后端 =========="

  echo ">> 同步 cf-worker/ 到服务器（排除 node_modules/、data/、uploads/、.env）..."
  do_rsync "cf-worker/" "${APP_DIR}/cf-worker/" "--exclude node_modules/ --exclude data/ --exclude uploads/ --exclude .env"

  echo ">> 同步 skill 包文件 cf-worker/uploads/ 到服务器..."
  do_rsync "cf-worker/uploads/" "${APP_DIR}/cf-worker/uploads/"

  echo ">> 在服务器上安装依赖并重启服务..."
  do_ssh "cd ${APP_DIR}/cf-worker && npm install --omit=dev && set -a && . ./.env && set +a && node scripts/db-init.cjs && pm2 restart ${PM2_NAME}"

  echo ">> 后端部署完成"
}

# 执行部署
case "$MODE" in
  all)
    echo "模式: 全量部署（前端 + 后端）"
    deploy_frontend
    deploy_backend
    ;;
  frontend)
    echo "模式: 仅部署前端"
    deploy_frontend
    ;;
  backend)
    echo "模式: 仅部署后端"
    deploy_backend
    ;;
  *)
    echo "错误: 未知模式 '$MODE'"
    echo "可选: all | frontend | backend"
    exit 1
    ;;
esac

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