#!/bin/bash
set -e

# ============================================================
# Diretta Target 安装 / 卸载管理脚本
#
# 用法：
#   sudo ./diretta_target_manager.sh install
#   sudo ./diretta_target_manager.sh install /path/to/diretta_target_pkg.tar.gz
#   sudo ./diretta_target_manager.sh uninstall
#
# 默认数据包地址：
#   https://s2.bravo123.top/diretta_target_pkg.tar.gz
# 优先使用同目录或指定路径的本地数据包，否则自动下载。
# ============================================================

TARGET_DIR="/opt/DirettaTarget"
KERNEL_SVC="/etc/systemd/system/diretta_kernel.service"
TARGET_SVC="/etc/systemd/system/diretta_target.service"

PKG_URL="https://s2.bravo123.top/diretta_target_pkg.tar.gz"
PKG_NAME="diretta_target_pkg.tar.gz"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOCAL_PKG="${SCRIPT_DIR}/${PKG_NAME}"

ACTION="${1:-}"
PKG_ARG="${2:-}"

usage() {
    echo "用法："
    echo "  sudo $0 install                         # 自动下载或使用本地数据包安装"
    echo "  sudo $0 install /path/to/pkg.tar.gz     # 指定本地数据包安装"
    echo "  sudo $0 uninstall"
    echo
    echo "默认数据包地址：${PKG_URL}"
    exit 1
}

require_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo "错误：请使用 root 权限运行，例如：sudo $0 ${ACTION}"
        exit 1
    fi
}

download_pkg() {
    local dst="$1"

    echo "下载数据包：${PKG_URL}"
    if command -v curl >/dev/null 2>&1; then
        curl -fL --connect-timeout 15 -o "${dst}" "${PKG_URL}"
    elif command -v wget >/dev/null 2>&1; then
        wget -O "${dst}" "${PKG_URL}"
    else
        echo "错误：系统缺少 curl 或 wget，无法下载。"
        exit 1
    fi

    if [ ! -s "${dst}" ]; then
        echo "错误：下载失败或文件为空：${dst}"
        exit 1
    fi
}

install_diretta() {
    require_root

    local pkg_path=""
    local TMP_DL=""

    if [ -n "${PKG_ARG}" ]; then
        if [ ! -f "${PKG_ARG}" ]; then
            echo "错误：找不到指定数据包：${PKG_ARG}"
            exit 1
        fi
        pkg_path="${PKG_ARG}"
        echo "使用指定数据包：${pkg_path}"
    elif [ -f "${LOCAL_PKG}" ]; then
        pkg_path="${LOCAL_PKG}"
        echo "使用同目录数据包：${pkg_path}"
    else
        echo "本地未发现数据包，准备自动下载。"
        TMP_DL="$(mktemp -d /tmp/diretta-dl.XXXXXX)"
        pkg_path="${TMP_DL}/${PKG_NAME}"
        download_pkg "${pkg_path}"
    fi

    echo
    echo "=== Diretta Target 安装开始 ==="
    echo "数据包：${pkg_path}"
    echo

    TMP_DIR="$(mktemp -d /tmp/diretta-install.XXXXXX)"
    trap 'rm -rf "${TMP_DIR}" "${TMP_DL}"' EXIT

    echo "[1/5] 解压数据包 ..."
    tar -xzpf "${pkg_path}" -C "${TMP_DIR}"

    if [ ! -d "${TMP_DIR}/opt/DirettaTarget" ]; then
        echo "错误：数据包中找不到 opt/DirettaTarget"
        exit 1
    fi

    echo "[2/5] 停止已有服务（如果存在）"
    systemctl stop diretta_target.service 2>/dev/null || true
    systemctl stop diretta_kernel.service 2>/dev/null || true

    echo "[3/5] 复制文件到 ${TARGET_DIR}"
    mkdir -p "${TARGET_DIR}"
    cp -a "${TMP_DIR}/opt/DirettaTarget/." "${TARGET_DIR}/"

    echo "[4/5] 设置权限"
    chown -R root:root "${TARGET_DIR}"
    chmod -R u+rwX,go+rX "${TARGET_DIR}"
    [ -f "${TARGET_DIR}/target_startup.sh" ] && chmod +x "${TARGET_DIR}/target_startup.sh"
    [ -f "${TARGET_DIR}/diretta_app_target" ] && chmod +x "${TARGET_DIR}/diretta_app_target"
    find "${TARGET_DIR}" -maxdepth 1 -type f \( -name "*.sh" -o -name "diretta_*" \) -exec chmod +x {} \; 2>/dev/null || true

    echo "[5/5] 创建 systemd service 并启动"

    cat > "${KERNEL_SVC}" <<'EOF_KERNEL'
[Unit]
Description=Diretta Kernel Service
After=network-online.target
Requires=network-online.target

[Service]
Type=simple
ExecStart=/opt/DirettaTarget/target_startup.sh
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF_KERNEL

    cat > "${TARGET_SVC}" <<'EOF_TARGET'
[Unit]
Description=Diretta Target Application
Documentation=https://www.diretta.link/
After=network-online.target diretta_kernel.service
Requires=network-online.target diretta_kernel.service

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/opt/DirettaTarget
ExecStart=/opt/DirettaTarget/diretta_app_target
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=10
TimeoutStartSec=30
TimeoutStopSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=diretta_target

[Install]
WantedBy=multi-user.target
EOF_TARGET

    systemctl daemon-reload
    systemctl enable diretta_kernel.service
    systemctl enable diretta_target.service

    systemctl restart diretta_kernel.service 2>/dev/null || true
    sleep 1
    systemctl restart diretta_target.service 2>/dev/null || true

    echo
    echo "=== 安装完成 ==="
    echo "查看状态："
    echo "  systemctl status diretta_kernel.service"
    echo "  systemctl status diretta_target.service"
    echo "查看日志："
    echo "  journalctl -u diretta_kernel.service -f"
    echo "  journalctl -u diretta_target.service -f"
}

uninstall_diretta() {
    require_root

    echo "=== Diretta Target 卸载开始 ==="

    echo "[1/4] 停止服务"
    systemctl stop diretta_target.service 2>/dev/null || true
    systemctl stop diretta_kernel.service 2>/dev/null || true

    echo "[2/4] 禁用服务并删除 service 文件"
    systemctl disable diretta_target.service 2>/dev/null || true
    systemctl disable diretta_kernel.service 2>/dev/null || true
    rm -f "${TARGET_SVC}" "${KERNEL_SVC}"

    echo "[3/4] 重新加载 systemd"
    systemctl daemon-reload
    systemctl reset-failed 2>/dev/null || true

    echo "[4/4] 删除 ${TARGET_DIR}"
    rm -rf "${TARGET_DIR}"

    echo
    echo "=== 卸载完成 ==="
}

case "${ACTION}" in
    install)
        install_diretta
        ;;
    uninstall)
        uninstall_diretta
        ;;
    *)
        usage
        ;;
esac
