#!/bin/bash

# 服务器配置信息
SERVER_IP="45.61.60.10"
SERVER_USER="root"
SERVER_PASS="UQb9TgSwC@vwhEM"
REMOTE_PARENT_DIR="/var/www/ccdw-website"

# 颜色输出
GREEN='\033[0;32m'
NC='\033[0m'

echo -e "${GREEN}=== 开始部署流程 ===${NC}"

# 1. 前端构建
echo -e "${GREEN}[1/5] 执行前端构建 (Vite Build)...${NC}"
npm run build
if [ $? -ne 0 ]; then
    echo "❌ 构建失败，请检查错误信息"
    exit 1
fi

# 2. 打包文件
echo -e "${GREEN}[2/5] 打包部署文件...${NC}"
rm -rf .deploy_temp
mkdir -p .deploy_temp
# 复制前端产物
cp -r dist .deploy_temp/
# 复制后端代码
cp -r server .deploy_temp/
# 删除不需要的文件
rm -rf .deploy_temp/server/node_modules 
rm -rf .deploy_temp/server/.DS_Store
rm -rf .deploy_temp/server/package-lock.json
# 进入临时目录打包
cd .deploy_temp
tar -czf ../release.tar.gz .
cd ..
rm -rf .deploy_temp
echo "✅ 打包完成: release.tar.gz"

# 3. 上传
echo -e "${GREEN}[3/5] 上传文件到服务器...${NC}"
/usr/bin/expect <<EOF
set timeout 300
spawn scp -o StrictHostKeyChecking=no release.tar.gz $SERVER_USER@$SERVER_IP:$REMOTE_PARENT_DIR/release.tar.gz
expect {
    "password:" { send "$SERVER_PASS\r" }
    "yes/no" { send "yes\r"; exp_continue }
}
expect eof
EOF

# 4. 远程部署
echo -e "${GREEN}[4/5] 服务器端部署...${NC}"

REMOTE_COMMANDS="
mkdir -p $REMOTE_PARENT_DIR && \
cd $REMOTE_PARENT_DIR && \
tar -xzf release.tar.gz && \
rm release.tar.gz && \
cd server && \
echo 'Installing dependencies...' && \
npm install --omit=dev --registry=https://registry.npmmirror.com && \
(command -v pm2 &> /dev/null || npm install -g pm2) && \
(pm2 describe ccdw-server > /dev/null 2>&1 && pm2 reload ccdw-server || pm2 start index.js --name ccdw-server) && \
pm2 save
"

/usr/bin/expect <<EOF
set timeout 300
spawn ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP "$REMOTE_COMMANDS"
expect {
    "password:" { send "$SERVER_PASS\r"; exp_continue }
    "yes/no" { send "yes\r"; exp_continue }
    eof
}
EOF

# 5. 清理本地
rm release.tar.gz

echo -e "${GREEN}=== 部署成功! ===${NC}"
echo -e "服务已启动在服务器的 3001 端口。"
echo -e "Node 服务现在同时也托管了前端页面 (http://IP:3001)。"
echo -e "如果您使用 Nginx，请配置反向代理将域名流量转发到 localhost:3001。"
