#!/bin/bash

# 系统服务自动部署脚本
# 功能：从指定URL下载服务程序，配置为Systemd服务并启动
# 需要root权限执行

SERVICE_NAME="agent-linux"
DOWNLOAD_URL="https://zfile.starss.cc/agent-linux-vps"
INSTALL_DIR="/usr/local/bin"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

# 检查root权限
if [ "$(id -u)" -ne 0 ]; then
    echo "错误：必须使用root权限运行此脚本"
    echo "请使用 sudo $0"
    exit 1
fi

# 检查依赖工具
check_dependencies() {
    for cmd in curl wget systemctl; do
        if ! command -v $cmd &> /dev/null; then
            echo "错误：未找到 $cmd 命令"
            exit 1
        fi
    done
}

# 下载服务程序
download_agent() {
    echo "正在下载服务程序..."

    TEMP_FILE=$(mktemp)
    if curl -fsSL -o "$TEMP_FILE" "$DOWNLOAD_URL"; then
        echo "下载成功"
    elif wget -q -O "$TEMP_FILE" "$DOWNLOAD_URL"; then
        echo "下载成功"
    else
        echo "错误：下载失败，请检查网络和URL"
        rm -f "$TEMP_FILE"
        exit 1
    fi

    # 安装到目标目录
    install -m 755 "$TEMP_FILE" "${INSTALL_DIR}/${SERVICE_NAME}"
    rm -f "$TEMP_FILE"
    echo "程序已安装到 ${INSTALL_DIR}/${SERVICE_NAME}"
}

# 创建系统服务
create_service() {
    cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=${SERVICE_NAME} Service
After=network.target

[Service]
ExecStart=${INSTALL_DIR}/${SERVICE_NAME}
Restart=always
RestartSec=3
User=root

[Install]
WantedBy=multi-user.target
EOF

    echo "服务配置文件已创建: ${SERVICE_FILE}"
}

# 启动服务
enable_service() {
    systemctl daemon-reload
    systemctl enable --now ${SERVICE_NAME} &> /dev/null

    if systemctl is-active --quiet ${SERVICE_NAME}; then
        echo "服务已成功启动!"
        echo "服务状态: systemctl status ${SERVICE_NAME}"
    else
        echo "错误：服务启动失败"
        journalctl -u ${SERVICE_NAME} -n 10 --no-pager
        exit 1
    fi
}

# 主执行流程
echo "===== 开始部署 ${SERVICE_NAME} 服务 ====="
check_dependencies
download_agent
create_service
enable_service
echo "===== 部署完成 ====="
