#!/bin/bash
# =============================================================================
# 智途投送 - 云端一键部署脚本
# 适用系统：Ubuntu 20.04 / 22.04 LTS
# 运行方式：root 用户执行  bash deploy.sh
# =============================================================================

set -e  # 遇到错误立即退出

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

PROJECT_DIR="/opt/zhitu"
SERVICE_NAME="zhitu"
NGINX_CONF="/etc/nginx/sites-available/zhitu"

echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}  智途投送 - 云端一键部署脚本${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""

# 检查是否 root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}错误：请使用 root 用户运行此脚本${NC}"
    echo "提示：先执行 sudo -i 切换到 root，再运行 bash deploy.sh"
    exit 1
fi

# 获取脚本所在目录（即后端代码目录）
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo -e "${YELLOW}[INFO]${NC} 后端代码目录: $SCRIPT_DIR"

# =============================================================================
# 步骤1: 更新系统并安装依赖
# =============================================================================
echo ""
echo -e "${GREEN}[1/8] 更新系统软件源...${NC}"
apt update -qq

echo -e "${GREEN}[2/8] 安装 Python3、Nginx、防火墙...${NC}"
apt install -y -qq python3 python3-pip python3-venv nginx curl ufw

# =============================================================================
# 步骤2: 创建项目目录并复制代码
# =============================================================================
echo -e "${GREEN}[3/8] 创建项目目录并复制代码...${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} 检测到本地存在 zhitu.db 数据库文件"
    read -p "是否将本地数据库复制到服务器？(y/n): " copy_db
    if [ "$copy_db" = "y" ] || [ "$copy_db" = "Y" ]; then
        cp "$SCRIPT_DIR/zhitu.db" "$PROJECT_DIR/zhitu.db"
        echo -e "${GREEN}已复制数据库${NC}"
    fi
fi

# =============================================================================
# 步骤3: 安装 Python 依赖
# =============================================================================
echo -e "${GREEN}[4/8] 安装 Python 依赖...${NC}"
cd "$PROJECT_DIR"
pip3 install -q -r requirements.txt

# =============================================================================
# 步骤4: 创建 Systemd 服务（比 Supervisor 更现代、更稳定）
# =============================================================================
echo -e "${GREEN}[5/8] 创建系统服务...${NC}"

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

[Service]
Type=simple
User=root
WorkingDirectory=${PROJECT_DIR}
ExecStart=/usr/local/bin/gunicorn -w 2 -b 127.0.0.1:5000 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}

# =============================================================================
# 步骤5: 配置 Nginx 反向代理
# =============================================================================
echo -e "${GREEN}[6/8] 配置 Nginx...${NC}"

cat > "$NGINX_CONF" << '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:5000;
        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;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # 静态文件直接由 Nginx 处理（提高效率）
    location /static {
        alias /opt/zhitu/static;
        expires 7d;
    }
}
EOF

# 启用配置，禁用默认站点
rm -f /etc/nginx/sites-enabled/default
ln -sf "$NGINX_CONF" /etc/nginx/sites-enabled/zhitu

# 测试 Nginx 配置
nginx -t

# =============================================================================
# 步骤6: 配置防火墙
# =============================================================================
echo -e "${GREEN}[7/8] 配置防火墙...${NC}"
ufw default deny incoming
ufw default allow outgoing
ufw allow 80/tcp      comment 'HTTP'
ufw allow 443/tcp     comment 'HTTPS'
ufw allow 22/tcp      comment 'SSH'
ufw --force enable

echo -e "${YELLOW}[提示]${NC} 防火墙已启用，仅开放 22(SSH)、80(HTTP)、443(HTTPS)"

# =============================================================================
# 步骤7: 启动服务
# =============================================================================
echo -e "${GREEN}[8/8] 启动服务...${NC}"
systemctl restart ${SERVICE_NAME}
systemctl restart nginx
sleep 2

# =============================================================================
# 部署完成，输出状态
# =============================================================================
echo ""
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}        部署完成！${NC}"
echo -e "${GREEN}=========================================${NC}"
echo ""

# 获取公网 IP
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null || curl -s icanhazip.com 2>/dev/null || echo "无法获取")

SERVICE_STATUS=$(systemctl is-active ${SERVICE_NAME})
NGINX_STATUS=$(systemctl is-active nginx)

echo -e "后端服务状态 : ${SERVICE_STATUS}"
echo -e "Nginx 状态   : ${NGINX_STATUS}"
echo -e "公网 IP      : ${PUBLIC_IP}"
echo ""
echo -e "访问地址:"
echo -e "  HTTP  : ${YELLOW}http://${PUBLIC_IP}${NC}"
echo -e "  或    : ${YELLOW}http://你的域名${NC} （如果已配置域名）"
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 ""
echo -e "${YELLOW}下一步:${NC}"
echo -e "  1. 打开单兵终端 APP，将服务器地址配置为: ${GREEN}http://${PUBLIC_IP}${NC}"
echo -e "  2. 如需 HTTPS，请先购买域名，然后运行: ${GREEN}certbot --nginx${NC}"
echo ""
