#!/bin/bash

#===============================================================================
# 少儿智慧阅读 - 一键部署到宝塔面板
#
# 使用方法:
#   ./deploy.sh your-server-ip
#   或
#   ./deploy.sh root@your-server-ip
#===============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_step() { echo -e "${BLUE}[STEP]${NC} $1"; }

# 检查参数
if [ -z "$1" ]; then
    echo ""
    echo "=============================================="
    echo "  少儿智慧阅读"
    echo "  一键部署到宝塔面板"
    echo "=============================================="
    echo ""
    echo "使用方法:"
    echo "  $0 your-server-ip"
    echo "  $0 root@your-server-ip"
    echo ""
    echo "示例:"
    echo "  $0 8.148.151.56"
    echo "  $0 root@8.148.151.56"
    echo ""
    exit 1
fi

# 解析参数
REMOTE_HOST="$1"
REMOTE_USER="root"
if [[ "$1" == *"@"* ]]; then
    REMOTE_USER=$(echo "$1" | cut -d'@' -f1)
    REMOTE_HOST=$(echo "$1" | cut -d'@' -f2)
fi

echo ""
echo "=============================================="
echo "  一键部署到宝塔面板"
echo "=============================================="
echo ""
echo "  服务器：$REMOTE_USER@$REMOTE_HOST"
echo ""

# 检查 SSH 连接
log_step "检查 SSH 连接..."
if ! ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "echo '连接成功'" 2>/dev/null; then
    log_error "SSH 连接失败，请检查:"
    echo "  1. 服务器 IP 是否正确"
    echo "  2. SSH 是否启用（默认端口 22）"
    echo "  3. 密码/密钥是否正确"
    echo ""
    echo "  如果是密码登录，请先执行："
    echo "  ssh-copy-id $REMOTE_USER@$REMOTE_HOST"
    exit 1
fi
log_info "SSH 连接成功"

# 检查远程服务器
log_step "检查远程服务器..."
ssh "$REMOTE_USER@$REMOTE_HOST" << 'ENDSSH'
    # 检查是否安装了宝塔
    if [ -d "/www/server/panel" ]; then
        echo "宝塔面板：已安装"
    else
        echo "警告：未检测到宝塔面板"
    fi

    # 检查 JDK
    if command -v java &> /dev/null; then
        java_version=$(java -version 2>&1 | head -n 1)
        echo "Java: $java_version"
    else
        echo "警告：未安装 Java"
    fi

    # 检查 MySQL
    if command -v mysql &> /dev/null; then
        echo "MySQL: 已安装"
    else
        echo "警告：未安装 MySQL"
    fi

    # 检查 Nginx
    if command -v nginx &> /dev/null; then
        echo "Nginx: 已安装"
    fi

    # 检查磁盘空间
    disk_used=$(df -h / | tail -1 | awk '{print $5}')
    echo "磁盘使用：$disk_used"
ENDSSH

echo ""
echo "=============================================="
echo "  部署前检查完成"
echo "=============================================="
echo ""
echo "  请确认:"
echo "  1. 宝塔面板已安装并可以访问"
echo "  2. 已在宝塔中安装 MySQL、Redis、Nginx"
echo "  3. 已创建数据库和用户（见 DEPLOY_BAOTA.md）"
echo "  4. JDK 17 已安装（或通过宝塔安装）"
echo ""
read -p "是否继续部署？(y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
fi

# 部署后端
log_step "部署后端..."
export REMOTE_USER
export REMOTE_HOST
bash "$SCRIPT_DIR/deploy-backend.sh"

# 部署前端
log_step "部署前端..."
bash "$SCRIPT_DIR/deploy-frontend.sh"

echo ""
echo "=============================================="
echo "  部署完成！"
echo "=============================================="
echo ""
echo "  下一步操作:"
echo ""
echo "  1. 在宝塔面板配置 Nginx 反向代理"
echo "     网站 → 设置 → 配置文件"
echo "     参考 nginx-baota.conf 中的配置"
echo ""
echo "  2. 验证后端服务"
echo "     ssh $REMOTE_USER@$REMOTE_HOST"
echo "     curl http://localhost:8480/actuator/health"
echo ""
echo "  3. 访问前端页面"
echo "     http://$REMOTE_HOST"
echo ""
echo "  4. 查看日志"
echo "     后端：tail -f /www/wwwroot/reading-platform/logs/app.log"
echo "     Nginx: tail -f /www/wwwlogs/你的域名.error.log"
echo ""
echo "=============================================="
