#!/bin/bash
# ============================================================
# server-setup.sh  阿里云轻量服务器 一键部署脚本
# 使用方式：
#   1. 把整个 aipro.tar.gz 上传到服务器 /home/aipro/
#   2. 在服务器执行：bash server-setup.sh
# ============================================================
set -e

APP_DIR=/home/aipro/app
DATA_DIR=/home/aipro/data
UPLOADS_DIR=/home/aipro/uploads

echo "=== [1/6] 安装 Node.js 22 ==="
NODE_MAJOR=$(node -e 'process.stdout.write(process.versions.node.split(".")[0])' 2>/dev/null || echo 0)
if [ "$NODE_MAJOR" -lt 22 ] 2>/dev/null; then
  echo "    当前 Node.js 版本不满足，使用 NodeSource 安装 v22..."
  # 检测发行版
  if [ -f /etc/debian_version ] || grep -qi ubuntu /etc/os-release 2>/dev/null; then
    # Ubuntu / Debian
    apt-get update -q
    apt-get install -y -q curl ca-certificates
    curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
    apt-get install -y -q nodejs
  elif [ -f /etc/redhat-release ] || grep -qi 'centos\|rhel\|aliyun' /etc/os-release 2>/dev/null; then
    # CentOS / RHEL / Alibaba Cloud Linux
    yum install -y curl
    curl -fsSL https://rpm.nodesource.com/setup_22.x | bash -
    yum install -y nodejs
  else
    echo "    ❌ 无法识别发行版，请手动安装 Node.js 22"
    exit 1
  fi
else
  echo "    Node.js $(node -v) ✓"
fi

echo "=== [2/6] 解压应用包 ==="
mkdir -p $APP_DIR $DATA_DIR $UPLOADS_DIR
cd /home/aipro
tar xzf aipro.tar.gz -C $APP_DIR
echo "    ✓ 解压完成"

echo "=== [3/6] 安装依赖 ==="
cd $APP_DIR/cf-worker
npm install --omit=dev
echo "    ✓ npm install 完成"

echo "=== [4/6] 初始化数据库 ==="
export DB_PATH=$DATA_DIR/aipro.db
export UPLOADS_DIR=$UPLOADS_DIR
node scripts/db-init.cjs
echo "    ✓ 数据库初始化完成"

echo "=== [5/6] 生成 .env 配置 ==="
cat > $APP_DIR/cf-worker/.env << EOF
PORT=4000
DB_PATH=$DATA_DIR/aipro.db
UPLOADS_DIR=$UPLOADS_DIR
DIST_DIR=$APP_DIR/dist
ALLOW_ORIGINS=*
EOF
echo "    ✓ .env 写入完成"

echo "=== [6/6] 安装 PM2 并启动服务 ==="
npm install -g pm2 2>/dev/null || true
cd $APP_DIR/cf-worker
pm2 delete aipro 2>/dev/null || true
pm2 start server.js --name aipro --cwd $APP_DIR/cf-worker
pm2 save
pm2 startup 2>/dev/null | grep "sudo" | bash 2>/dev/null || true

echo ""
echo "========================================"
echo "✅ 部署完成！"
echo "   访问：http://$(curl -s ifconfig.me):4000"
echo "   PM2 状态：pm2 status"
echo "   日志：pm2 logs aipro"
echo "========================================"
