#!/bin/bash

# 服务器配置信息
SERVER_IP="47.253.147.187"
SERVER_USER="root"
SERVER_PASS="5H0FuZ:2s0q)Lx"
REMOTE_PARENT_DIR="/www/wwwroot/ccdw-website" # 项目父目录

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

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

# 1. 本地构建 (Vite Build)
echo -e "${GREEN}正在执行本地构建 (npm run build)...${NC}"
npm run build

if [ $? -ne 0 ]; then
    echo "构建失败，请检查错误信息"
    exit 1
fi

# 2. 压缩构建产物
echo -e "${GREEN}正在打包构建产物...${NC}"
if [ -d "dist" ]; then
    cd dist
    # 打包所有文件到 release.tar.gz
    tar -czf ../release.tar.gz .
    cd ..
    echo "打包完成: release.tar.gz"
else
    echo "错误: 未找到 dist 目录"
    exit 1
fi

# 3. 上传文件 (使用 expect 自动输入密码)
echo -e "${GREEN}正在上传文件到服务器...${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}正在服务器上解压并部署...${NC}"
/usr/bin/expect <<EOF
set timeout 30
spawn ssh -o StrictHostKeyChecking=no $SERVER_USER@$SERVER_IP
expect {
    "password:" { send "$SERVER_PASS\r" }
    "yes/no" { send "yes\r"; exp_continue }
}
expect "#"
# 进入目录
send "mkdir -p $REMOTE_PARENT_DIR/public\r"
send "cd $REMOTE_PARENT_DIR\r"
# 解压覆盖到 public 目录
send "tar -xzf release.tar.gz -C public\r"
# 清理压缩包
send "rm release.tar.gz\r"
# 修正权限 (假设 web 用户为 www，如果不是宝塔面板可能需要调整)
send "chown -R www:www public\r"
send "chmod -R 755 public\r"
send "exit\r"
expect eof
EOF

echo -e "${GREEN}部署完成! 请访问 https://ccdw.xyz${NC}"

# 5. 清理本地压缩包
rm release.tar.gz
