#!/bin/bash
set -e

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

# 解析参数
USER_NAME="ramy"
INSTALL_DIR="/home/ramy/task_manager"
PORT="80"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --install-dir)
            INSTALL_DIR="$2"
            shift 2
            ;;
        --user)
            USER_NAME="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: sudo ./deploy.sh [--install-dir PATH] [--user USER] [--port PORT]"
            echo "  --install-dir  安装目录 (默认: /home/ramy/task_manager)"
            echo "  --user         运行用户 (默认: ramy)"
            echo "  --port         监听端口 (默认: 80)"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            echo "使用 --help 查看帮助"
            exit 1
            ;;
    esac
done

SERVICE_NAME="drone-task-manager"

echo "========================================"
echo "Drone Task Manager 部署脚本"
echo "========================================"
echo ""
echo "安装目录: ${INSTALL_DIR}"
echo "运行用户: ${USER_NAME}"
echo "服务端口: ${PORT}"
echo ""

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then
    echo "错误: 请使用 sudo 运行此脚本"
    echo "示例: sudo ./deploy.sh"
    exit 1
fi

# 检查 Python3
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到 python3，请先安装 Python 3.8+"
    exit 1
fi

PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
echo "Python 版本: $PYTHON_VERSION"

# 检查 pip
if ! command -v pip3 &> /dev/null && ! python3 -m pip --version &> /dev/null; then
    echo "错误: 未找到 pip，请先安装 pip"
    exit 1
fi

# 如果服务正在运行，先停止
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    echo ""
    echo "[1/8] 停止现有服务..."
    systemctl stop "$SERVICE_NAME"
    echo "  ✓ 服务已停止"
fi

# 复制项目到安装目录
if [ "$SCRIPT_DIR" != "$INSTALL_DIR" ]; then
    echo ""
    echo "[2/8] 安装项目到 ${INSTALL_DIR}..."
    mkdir -p "$INSTALL_DIR"
    rsync -a --delete --exclude='.venv' --exclude='node_modules' --exclude='__pycache__' \
          --exclude='.git' --exclude='*.pyc' --exclude='.pytest_cache' \
          --exclude='data/' --exclude='models/' \
          --exclude='push_streams.json' --exclude='detection_config.json' --exclude='detection_alerts.jsonl' \
          --exclude='*.tar.gz' \
          "$SCRIPT_DIR/" "$INSTALL_DIR/"
    chown -R "${USER_NAME}:${USER_NAME}" "$INSTALL_DIR"
    # 确保 go2rtc 有执行权限
    if [ -f "${INSTALL_DIR}/media/go2rtc" ]; then
        chmod +x "${INSTALL_DIR}/media/go2rtc"
        echo "  ✓ go2rtc 权限已设置"
    fi
    echo "  ✓ 项目已复制到 ${INSTALL_DIR}（旧文件已清理）"
else
    echo ""
    echo "[2/8] 当前目录已是安装目录，跳过复制"
fi

cd "$INSTALL_DIR"

# 创建虚拟环境
echo ""
echo "[3/8] 创建虚拟环境..."
if [ ! -d ".venv" ]; then
    if python3 -m venv .venv 2>/dev/null; then
        chown -R "${USER_NAME}:${USER_NAME}" .venv
        echo "  ✓ 虚拟环境已创建"
    else
        echo "  ! python3-venv 未安装，尝试 --without-pip 模式..."
        python3 -m venv --without-pip .venv
        chown -R "${USER_NAME}:${USER_NAME}" .venv
        source .venv/bin/activate
        echo "  → 手动安装 pip（离线模式）..."
        if [ -f "${INSTALL_DIR}/get-pip.py" ] && [ -d "${INSTALL_DIR}/deps" ]; then
            python "${INSTALL_DIR}/get-pip.py" --no-index --find-links "${INSTALL_DIR}/deps/" --no-warn-script-location
            echo "  ✓ 虚拟环境已创建（pip 由 get-pip.py 离线安装）"
        elif [ -f "${INSTALL_DIR}/get-pip.py" ]; then
            python "${INSTALL_DIR}/get-pip.py" --no-warn-script-location
            echo "  ✓ 虚拟环境已创建（pip 由 get-pip.py 安装，可能需联网）"
        else
            echo "  ✗ 失败: get-pip.py 不存在且 python3-venv 未安装"
            echo "    请安装 python3-venv: sudo apt-get install python3-venv"
            exit 1
        fi
    fi
else
    echo "  ✓ 虚拟环境已存在，跳过"
fi

# 安装依赖
echo ""
echo "[4/8] 安装 Python 依赖..."
source .venv/bin/activate

TSINGHUA_INDEX="https://pypi.tuna.tsinghua.edu.cn/simple"
HAS_DEPS=0
if [ -d "deps" ] && [ "$(ls -A deps 2>/dev/null)" ]; then
    HAS_DEPS=1
fi

# 优先离线升级 pip
if [ "$HAS_DEPS" -eq 1 ]; then
    echo "  → 尝试离线升级 pip..."
    if pip install --no-index --find-links deps/ --upgrade pip -q 2>/dev/null; then
        echo "  ✓ pip 已离线升级"
    else
        echo "  ! pip 离线升级失败，尝试联网..."
        pip install --upgrade pip -q -i "$TSINGHUA_INDEX"
        echo "  ✓ pip 已升级"
    fi
else
    pip install --upgrade pip -q -i "$TSINGHUA_INDEX"
    echo "  ✓ pip 已升级"
fi

# 安装项目依赖
if [ "$HAS_DEPS" -eq 1 ]; then
    echo "  → 尝试从本地 deps/ 离线安装..."
    if pip install --no-index --find-links deps/ -r requirements.txt -q 2>/dev/null; then
        echo "  ✓ 依赖已从本地 deps/ 安装完成（完全离线）"
    else
        echo "  ! 本地安装失败（平台不兼容或缺失），回退到清华源..."
        pip install -r requirements.txt -q -i "$TSINGHUA_INDEX"
        echo "  ✓ 依赖已从清华源安装完成"
    fi
else
    echo "  → 本地 deps/ 不存在，从清华源下载安装..."
    pip install -r requirements.txt -q -i "$TSINGHUA_INDEX"
    echo "  ✓ 依赖已从清华源安装完成"
fi

# 创建状态文件目录
echo ""
echo "[5/8] 配置状态持久化目录..."
STATE_DIR="${INSTALL_DIR}/data"
if [ ! -d "$STATE_DIR" ]; then
    mkdir -p "$STATE_DIR"
    chown "$USER_NAME:$USER_NAME" "$STATE_DIR"
    echo "  ✓ 创建状态目录: $STATE_DIR"
else
    echo "  ✓ 状态目录已存在: $STATE_DIR"
fi

# 安装 systemd 服务
echo ""
echo "[6/8] 安装 systemd 服务..."
"$INSTALL_DIR/install_service.sh" --user "$USER_NAME"

# 更新 service 文件，添加状态文件参数
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
if grep -q "--state-file" "$SERVICE_FILE" 2>/dev/null; then
    echo "  ✓ 状态文件参数已配置"
else
    sed -i "s|main.py --host 0.0.0.0 --port ${PORT}|main.py --host 0.0.0.0 --port ${PORT} --state-file ${STATE_DIR}/state.json|" "$SERVICE_FILE"
    systemctl daemon-reload
    echo "  ✓ 已添加状态持久化配置: ${STATE_DIR}/state.json"
fi

# 停止并禁用 nginx（如果存在）
echo ""
echo "[7/8] 停止并禁用 nginx..."
if command -v nginx &> /dev/null; then
    if systemctl is-active --quiet nginx 2>/dev/null; then
        systemctl stop nginx
        echo "  ✓ nginx 已停止"
    else
        echo "  ✓ nginx 未在运行"
    fi
    if systemctl is-enabled --quiet nginx 2>/dev/null; then
        systemctl disable nginx
        echo "  ✓ nginx 已禁用开机自启"
    else
        echo "  ✓ nginx 已禁用或未配置"
    fi
else
    echo "  ✓ 未找到 nginx，跳过"
fi

# 停止并禁用旧的上传服务 uploader.service
echo ""
echo "[8/8] 停止并禁用旧的上传服务 uploader.service..."
if systemctl is-active --quiet uploader.service 2>/dev/null; then
    systemctl stop uploader.service
    echo "  ✓ uploader.service 已停止"
else
    echo "  ✓ uploader.service 未在运行"
fi
if systemctl is-enabled --quiet uploader.service 2>/dev/null; then
    systemctl disable uploader.service
    echo "  ✓ uploader.service 已禁用开机自启"
else
    echo "  ✓ uploader.service 已禁用或未配置"
fi

# 启动服务
echo ""
echo "启动服务..."
systemctl start "$SERVICE_NAME"
sleep 2

# 检查服务状态
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "  ✓ 服务启动成功"
else
    echo "  ✗ 服务启动失败，请检查日志:"
    echo "    journalctl -u $SERVICE_NAME -n 20 --no-pager"
    exit 1
fi

echo ""
echo "========================================"
echo "部署完成!"
echo "========================================"
echo ""
echo "访问地址:"
echo "  Web 管理界面: http://<无人机IP>/"
echo "  API 文档:     http://<无人机IP>/docs"
echo "  探测端点:     http://<无人机IP>/api/test"
echo ""
echo "常用命令:"
echo "  查看状态: sudo systemctl status $SERVICE_NAME"
echo "  查看日志: sudo journalctl -u $SERVICE_NAME -f"
echo "  重启服务: sudo systemctl restart $SERVICE_NAME"
echo "  停止服务: sudo systemctl stop $SERVICE_NAME"
echo ""
echo "安装目录:     ${INSTALL_DIR}"
echo "状态持久化:   ${STATE_DIR}/state.json"
echo "任务配置:     ${INSTALL_DIR}/tasks/"
echo ""
