#!/bin/bash
# Soul项目一键部署到宝塔服务器
# 使用方法: ./deploy-to-server.sh [SSH密码]

# 服务器配置
SERVER_IP="42.194.232.22"
SERVER_USER="root"
PROJECT_PATH="/www/wwwroot/soul"
BRANCH="soul-content"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "======================================="
echo "  Soul项目 - 宝塔服务器一键部署"
echo "======================================="
echo ""

# 检查sshpass是否安装
if ! command -v sshpass &> /dev/null; then
    echo -e "${YELLOW}正在安装sshpass...${NC}"
    brew install hudochenkov/sshpass/sshpass 2>/dev/null || {
        echo -e "${RED}请手动安装sshpass: brew install hudochenkov/sshpass/sshpass${NC}"
        exit 1
    }
fi

# 获取SSH密码
if [ -z "$1" ]; then
    echo -n "请输入SSH密码: "
    read -s SSH_PASSWORD
    echo ""
else
    SSH_PASSWORD="$1"
fi

echo ""
echo -e "${GREEN}[1/5]${NC} 连接服务器..."

# 测试连接
sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 $SERVER_USER@$SERVER_IP "echo '连接成功'" 2>/dev/null
if [ $? -ne 0 ]; then
    echo -e "${RED}连接失败，请检查密码是否正确${NC}"
    exit 1
fi

echo -e "${GREEN}[2/5]${NC} 拉取最新代码..."
sshpass -p "$SSH_PASSWORD" ssh $SERVER_USER@$SERVER_IP "cd $PROJECT_PATH && git fetch origin && git reset --hard origin/$BRANCH"

echo -e "${GREEN}[3/5]${NC} 安装依赖..."
sshpass -p "$SSH_PASSWORD" ssh $SERVER_USER@$SERVER_IP "cd $PROJECT_PATH && pnpm install --frozen-lockfile 2>/dev/null || npm install"

echo -e "${GREEN}[4/5]${NC} 构建项目..."
sshpass -p "$SSH_PASSWORD" ssh $SERVER_USER@$SERVER_IP "cd $PROJECT_PATH && pnpm build 2>/dev/null || npm run build"

echo -e "${GREEN}[5/5]${NC} 重启服务..."
# 使用www用户的PM2（宝塔方式）
sshpass -p "$SSH_PASSWORD" ssh $SERVER_USER@$SERVER_IP "sudo -u www /www/server/nvm/versions/node/*/bin/pm2 restart soul 2>/dev/null || pm2 restart soul"

echo ""
echo "======================================="
echo -e "${GREEN}✅ 部署完成！${NC}"
echo "======================================="
echo ""
echo "访问地址: https://soul.quwanzhi.com"
echo ""

# 测试API
echo "正在验证部署..."
sleep 3
curl -s "https://soul.quwanzhi.com/api/book/chapter/1.1" | head -100
