#!/bin/bash
set -e

SERVICE_NAME="drone-task-manager"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
USER_NAME="ramy"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --user)
            USER_NAME="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: sudo ./install_service.sh [--user USER]"
            echo "  --user  运行用户 (默认: ramy)"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

if [ "$EUID" -ne 0 ]; then
    echo "请使用 sudo 运行此脚本"
    exit 1
fi

if [ ! -d "${SCRIPT_DIR}/.venv" ]; then
    echo "错误: 未找到虚拟环境 ${SCRIPT_DIR}/.venv"
    echo "请先运行: python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt"
    exit 1
fi

echo "安装 Drone Task Manager 系统服务..."
echo "  工作目录: ${SCRIPT_DIR}"
echo "  运行用户: ${USER_NAME}"

# 生成 service 文件
sed -e "s|{{USER}}|${USER_NAME}|g" \
    -e "s|{{WORKING_DIR}}|${SCRIPT_DIR}|g" \
    -e "s|{{VENV_BIN}}|${SCRIPT_DIR}/.venv/bin|g" \
    "${SCRIPT_DIR}/systemd/drone-task-manager.service.template" > "${SERVICE_FILE}"

chmod 644 "${SERVICE_FILE}"

# 配置 sudoers，允许服务用户免密操作自身服务及任意 *.service
SUDOERS_FILE="/etc/sudoers.d/${SERVICE_NAME}"
SYSCTL_CMD="$(command -v systemctl)"
SUDOERS_LINE="${USER_NAME} ALL=(ALL) NOPASSWD: ${SYSCTL_CMD} restart ${SERVICE_NAME}, ${SYSCTL_CMD} start ${SERVICE_NAME}, ${SYSCTL_CMD} stop ${SERVICE_NAME}, ${SYSCTL_CMD} start *.service, ${SYSCTL_CMD} stop *.service, ${SYSCTL_CMD} restart *.service"
if [ ! -f "$SUDOERS_FILE" ]; then
    echo "$SUDOERS_LINE" > "$SUDOERS_FILE"
    chmod 440 "$SUDOERS_FILE"
    echo "  ✓ sudoers 已配置（免密操作 *.service, cmd=${SYSCTL_CMD}）"
else
    # 更新为通配符版本（支持任意 service，无需逐条列出）
    echo "$SUDOERS_LINE" > "$SUDOERS_FILE"
    chmod 440 "$SUDOERS_FILE"
    echo "  ✓ sudoers 已更新（免密操作 *.service, cmd=${SYSCTL_CMD}）"
fi

# 重载 systemd
systemctl daemon-reload

# 启用开机自启
systemctl enable "${SERVICE_NAME}.service"

# 停止并禁用 nginx（如果存在）
if command -v nginx &> /dev/null; then
    if systemctl is-active --quiet nginx 2>/dev/null; then
        systemctl stop nginx
        echo "  ✓ nginx 已停止"
    fi
    if systemctl is-enabled --quiet nginx 2>/dev/null; then
        systemctl disable nginx
        echo "  ✓ nginx 已禁用开机自启"
    fi
fi

echo ""
echo "服务已安装并启用开机自启。"
echo "  启动: sudo systemctl start ${SERVICE_NAME}"
echo "  停止: sudo systemctl stop ${SERVICE_NAME}"
echo "  状态: sudo systemctl status ${SERVICE_NAME}"
echo "  日志: sudo journalctl -u ${SERVICE_NAME} -f"
