#!/bin/bash
# =============================================================================
# 智途投送 - 安全部署脚本（自动检测冲突、自适应端口）
# 适用：已部署其他项目的共享服务器
# =============================================================================

set -e

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

PROJECT_DIR="/opt/zhitu"
SERVICE_NAME="zhitu"

echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}  智途投送 - 安全部署脚本${NC}"
echo -e "${GREEN}  （自动检测冲突 + 自适应端口）${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""

if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}错误：请使用 root 用户运行${NC}"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# =============================================================================
# 自动检测端口占用，选择可用端口
# =============================================================================
echo -e "${BLUE}[检测]${NC} 检查端口占用情况..."

BASE_PORT=5000
PORT=$BASE_PORT
while ss -tlnp 2>/dev/null | grep -q ":$PORT\b" || netstat -tlnp 2>/dev/null | grep -q ":$PORT\b"; do
    PORT=$((PORT + 1))
    if [ $PORT -gt 5100 ]; then
        echo -e "${RED}错误：5000-5100 端口全部被占用，请手动清理${NC}"
        exit 1
    fi
done

echo -e "${GREEN}  ✓ 后端将使用端口: $PORT${NC}"

# =============================================================================
# 检测 Nginx 状态
# =============================================================================
NGINX_ACTIVE=false
if systemctl is-active --quiet nginx 2>/dev/null || service nginx status 2>/dev/null | grep -q running; then
    NGINX_ACTIVE=true
    echo -e "${YELLOW}  ! 检测到 Nginx 已在运行（其他项目正在使用 80 端口）${NC}"
    echo -e "${YELLOW}    智途投送将直接暴露在高端口 $PORT，不占用 80 端口${NC}"
else
    echo -e "${GREEN}  ✓ 80 端口空闲，将配置 Nginx 反向代理${NC}"
fi

# =============================================================================
# 检测 /opt/zhitu 是否已存在（防止覆盖其他项目）
# =============================================================================
if [ -d "$PROJECT_DIR" ]; then
    echo -e "${YELLOW}[警告]${NC} 检测到目录 $PROJECT_DIR 已存在"
    BACKUP_DIR="${PROJECT_DIR}.backup.$(date +%Y%m%d%H%M%S)"
    echo -e "${YELLOW}       自动备份到: $BACKUP_DIR${NC}"
    mv "$PROJECT_DIR" "$BACKUP_DIR"
fi

# =============================================================================
# 安装依赖
# =============================================================================
echo ""
echo -e "${GREEN}[1/5] 安装环境依赖...${NC}"
apt update -qq
apt install -y -qq python3 python3-pip python3-venv curl

# =============================================================================
# 复制代码
# =============================================================================
echo -e "${GREEN}[2/5] 复制后端代码...${NC}"
mkdir -p "$PROJECT_DIR"
rsync -av --exclude='zhitu.db' "$SCRIPT_DIR/" "$PROJECT_DIR/" 2>/dev/null || cp -r "$SCRIPT_DIR"/* "$PROJECT_DIR/"

# 如果本地有数据库，询问是否复制
if [ -f "$SCRIPT_DIR/zhitu.db" ]; then
    echo -e "${YELLOW}[提示]${NC} 检测到本地数据库文件"
    # 非交互式环境直接复制（课程服务器通常自动化部署）
    cp "$SCRIPT_DIR/zhitu.db" "$PROJECT_DIR/zhitu.db" 2>/dev/null && echo -e "${GREEN}  ✓ 已复制数据库${NC}" || true
fi

# =============================================================================
# 安装 Python 依赖
# =============================================================================
echo -e "${GREEN}[3/5] 创建虚拟环境并安装依赖...${NC}"
cd "$PROJECT_DIR"
# Ubuntu 24.04 禁止直接 pip 安装到系统，使用虚拟环境
if [ ! -d "$PROJECT_DIR/venv" ]; then
    python3 -m venv venv
fi
source "$PROJECT_DIR/venv/bin/activate"
pip install -q -r requirements.txt

# =============================================================================
# 创建 Systemd 服务
# =============================================================================
echo -e "${GREEN}[4/5] 创建后端服务...${NC}"

# 如果存在旧服务，先停止
systemctl stop ${SERVICE_NAME} 2>/dev/null || true
systemctl disable ${SERVICE_NAME} 2>/dev/null || true
rm -f /etc/systemd/system/${SERVICE_NAME}.service

cat > /etc/systemd/system/${SERVICE_NAME}.service << EOF
[Unit]
Description=智途投送后端服务 (Port $PORT)
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=${PROJECT_DIR}
ExecStart=${PROJECT_DIR}/venv/bin/gunicorn -w 2 -b 0.0.0.0:${PORT} app:app
Restart=always
RestartSec=5
StandardOutput=append:/var/log/zhitu.log
StandardError=append:/var/log/zhitu.log

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable ${SERVICE_NAME}
systemctl restart ${SERVICE_NAME}

sleep 2

# =============================================================================
# 配置 Nginx（仅在 Nginx 未运行时）
# =============================================================================
if [ "$NGINX_ACTIVE" = false ]; then
    echo -e "${GREEN}[5/5] 配置 Nginx...${NC}"
    apt install -y -qq nginx
    
    cat > /etc/nginx/sites-available/zhitu << EOF
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    client_max_body_size 20M;

    location / {
        proxy_pass http://127.0.0.1:${PORT};
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }
}
EOF
    rm -f /etc/nginx/sites-enabled/default
    ln -sf /etc/nginx/sites-available/zhitu /etc/nginx/sites-enabled/zhitu
    nginx -t && systemctl restart nginx
    
    # 防火墙
    ufw allow 80/tcp 2>/dev/null || true
    ufw allow 443/tcp 2>/dev/null || true
    ufw allow 22/tcp 2>/dev/null || true
else
    echo -e "${GREEN}[5/5] 跳过 Nginx 配置（已被其他项目占用）${NC}"
    # 只开放智途使用的端口
    ufw allow ${PORT}/tcp 2>/dev/null || true
fi

# =============================================================================
# 输出结果
# =============================================================================
echo ""
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}        部署完成！${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""

PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null || curl -s icanhazip.com 2>/dev/null || echo "你的服务器IP")
SERVICE_STATUS=$(systemctl is-active ${SERVICE_NAME} 2>/dev/null || echo "unknown")

echo -e "后端服务状态 : ${SERVICE_STATUS}"
echo -e "使用端口     : ${YELLOW}${PORT}${NC}"
echo -e "公网 IP      : ${PUBLIC_IP}"
echo ""

if [ "$NGINX_ACTIVE" = true ]; then
    echo -e "访问地址（直接端口）:"
    echo -e "  ${YELLOW}http://${PUBLIC_IP}:${PORT}${NC}"
    echo ""
    echo -e "${YELLOW}提示:${NC} 由于 80 端口被其他项目占用，"
    echo -e "      单兵终端请配置为: ${GREEN}http://${PUBLIC_IP}:${PORT}${NC}"
else
    echo -e "访问地址:"
    echo -e "  HTTP  : ${YELLOW}http://${PUBLIC_IP}${NC}"
    echo -e "  或    : ${YELLOW}http://${PUBLIC_IP}:${PORT}${NC}"
fi

echo ""
echo -e "常用命令:"
echo -e "  查看日志    : ${YELLOW}journalctl -u zhitu -f${NC}"
echo -e "  重启服务    : ${YELLOW}systemctl restart zhitu${NC}"
echo -e "  查看状态    : ${YELLOW}systemctl status zhitu${NC}"
echo -e "  数据库位置  : ${YELLOW}${PROJECT_DIR}/zhitu.db${NC}"
echo ""
