#!/bin/bash

# NodeMonitor Agent 安装脚本
# 用法:
#   备用服务器: curl -sSL https://your-server/install_agent.sh | bash -s -- <server_host> <node_id> <token>
#   主服务器:   curl -sSL https://your-server/install_agent.sh | bash -s -- <server_host> <node_id> <token> <port> --with-service

set -e

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

# 打印信息
info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
    exit 1
}

# 检查是否为 root 用户
check_root() {
    if [ "$EUID" -ne 0 ]; then
        error "请使用 root 用户运行此脚本"
    fi
}

# 检查系统类型
check_system() {
    if [ ! -f /etc/os-release ]; then
        error "不支持的操作系统"
    fi

    . /etc/os-release
    info "检测到系统: $NAME $VERSION"
}

# 安装依赖
install_dependencies() {
    info "检查依赖..."

    # 检查 systemd
    if ! command -v systemctl &> /dev/null; then
        error "系统不支持 systemd"
    fi
}

# 检测并卸载旧版本
uninstall_old_version() {
    if systemctl is-active --quiet nodemonitor-agent 2>/dev/null; then
        warn "检测到已安装的 Agent 服务，正在卸载..."

        # 停止并禁用服务
        systemctl stop nodemonitor-agent 2>/dev/null || true
        systemctl disable nodemonitor-agent 2>/dev/null || true

        info "已停止旧服务"
    fi

    # 删除旧文件
    if [ -f /opt/nodemonitor-agent/agent ]; then
        warn "删除旧的二进制文件..."
        rm -f /opt/nodemonitor-agent/agent
    fi

    if [ -d /opt/nodemonitor-agent ]; then
        warn "清理旧安装目录..."
        rm -rf /opt/nodemonitor-agent
    fi

    if [ -d /etc/nodemonitor-agent ]; then
        warn "清理旧配置目录..."
        rm -rf /etc/nodemonitor-agent
    fi

    if [ -f /etc/systemd/system/nodemonitor-agent.service ]; then
        warn "删除旧服务文件..."
        rm -f /etc/systemd/system/nodemonitor-agent.service
        systemctl daemon-reload
    fi

    info "旧版本清理完成"
}

# 验证下载的文件
verify_downloaded_file() {
    local file_path="$1"

    if [ ! -f "$file_path" ]; then
        error "文件不存在: $file_path"
    fi

    # 检查文件大小（HTML 文件通常很小）
    local file_size=$(stat -c%s "$file_path" 2>/dev/null || stat -f%z "$file_path" 2>/dev/null)
    if [ "$file_size" -lt 1000 ]; then
        error "下载的文件太小 ($file_size bytes)，可能是 HTML 页面而不是二进制文件"
    fi

    # 检查文件类型
    if command -v file &> /dev/null; then
        local file_type=$(file "$file_path")
        if echo "$file_type" | grep -qi "html\|text"; then
            error "下载的文件是 HTML/文本文件，不是可执行二进制文件。请检查下载 URL 配置"
        fi

        if ! echo "$file_type" | grep -qi "elf.*executable"; then
            error "下载的文件不是 Linux ELF 可执行文件: $file_type"
        fi

        info "文件验证通过: $(echo $file_type | grep -o 'ELF.*')"
    else
        warn "未安装 file 命令，跳过文件格式验证"
    fi
}

# 获取配置参数
get_config() {
    # 从命令行参数获取
    INSTALL_SERVICE=false

    if [ $# -ge 3 ]; then
        SERVER_HOST="$1"
        NODE_ID="$2"
        AGENT_TOKEN="$3"
        SERVER_PORT="${4:-8000}"

        # 检查是否有 --with-service 参数
        for arg in "$@"; do
            if [ "$arg" = "--with-service" ]; then
                INSTALL_SERVICE=true
                break
            fi
        done
    else
        # 交互式输入
        echo ""
        echo "========== NodeMonitor Agent 安装向导 =========="
        echo ""

        read -p "请输入服务器地址 (如: 166.88.61.180): " SERVER_HOST
        if [ -z "$SERVER_HOST" ]; then
            error "服务器地址不能为空"
        fi

        read -p "请输入服务器端口 [8000]: " SERVER_PORT
        SERVER_PORT=${SERVER_PORT:-8000}

        read -p "请输入节点 ID: " NODE_ID
        if [ -z "$NODE_ID" ]; then
            error "节点 ID 不能为空"
        fi

        read -p "请输入 Agent Token: " AGENT_TOKEN
        if [ -z "$AGENT_TOKEN" ]; then
            error "Agent Token 不能为空"
        fi

        read -p "是否安装业务服务? (主服务器选 y, 备用服务器选 n) [n]: " install_choice
        if [ "$install_choice" = "y" ] || [ "$install_choice" = "Y" ]; then
            INSTALL_SERVICE=true
        fi
    fi

    info "配置信息:"
    info "  服务器: $SERVER_HOST:$SERVER_PORT"
    info "  节点ID: $NODE_ID"
    info "  Token: ${AGENT_TOKEN:0:10}..."
    if [ "$INSTALL_SERVICE" = true ]; then
        info "  模式: 主服务器 (Agent + 业务服务)"
    else
        info "  模式: 备用服务器 (仅 Agent)"
    fi
}

# 下载 Agent 二进制文件
download_agent() {
    info "下载 Agent 程序..."

    # 创建目录
    mkdir -p /opt/nodemonitor-agent
    mkdir -p /etc/nodemonitor-agent

    # 检查是否本地有编译好的文件
    if [ -f "./linux_amd64/agent" ]; then
        info "使用本地文件"
        cp ./linux_amd64/agent /opt/nodemonitor-agent/agent
    else
        # 从服务器下载 (使用固定的下载服务端口 9990)
        DOWNLOAD_URL="http://166.88.61.180:9990/download/agent/agent"
        info "从 $DOWNLOAD_URL 下载..."

        if command -v wget &> /dev/null; then
            wget -O /opt/nodemonitor-agent/agent "$DOWNLOAD_URL" || error "下载失败"
        elif command -v curl &> /dev/null; then
            curl -L -o /opt/nodemonitor-agent/agent "$DOWNLOAD_URL" || error "下载失败"
        else
            error "需要 wget 或 curl 命令"
        fi
    fi

    # 验证下载的文件
    verify_downloaded_file /opt/nodemonitor-agent/agent

    chmod +x /opt/nodemonitor-agent/agent
    info "Agent 程序安装完成"
}

# 生成配置文件
generate_config() {
    info "生成配置文件..."

    cat > /etc/nodemonitor-agent/config.yaml <<EOF
# NodeMonitor Agent 配置文件
# 自动生成于: $(date)

# 服务器配置
server:
  host: "${SERVER_HOST}"
  port: ${SERVER_PORT}
  https: false

# Agent 配置
agent:
  node_id: ${NODE_ID}
  token: "${AGENT_TOKEN}"
  heartbeat_period: 30
  reconnect_period: 5
  version: "1.0.0"
EOF

    chmod 600 /etc/nodemonitor-agent/config.yaml
    info "配置文件已生成: /etc/nodemonitor-agent/config.yaml"
}

# 安装 systemd 服务
install_service() {
    info "安装 systemd 服务..."

    cat > /etc/systemd/system/nodemonitor-agent.service <<'EOF'
[Unit]
Description=NodeMonitor Agent
Documentation=https://github.com/yourorg/nodeMonitor
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/nodemonitor-agent
ExecStart=/opt/nodemonitor-agent/agent -config /etc/nodemonitor-agent/config.yaml
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

# 资源限制
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    info "systemd 服务已安装"
}

# 启动服务
start_service() {
    info "启动 Agent 服务..."

    systemctl enable nodemonitor-agent
    systemctl start nodemonitor-agent

    sleep 2

    if systemctl is-active --quiet nodemonitor-agent; then
        info "Agent 服务启动成功"
    else
        error "Agent 服务启动失败，请检查日志: journalctl -u nodemonitor-agent -f"
    fi
}

# 安装业务服务
install_business_service() {
    if [ "$INSTALL_SERVICE" = true ]; then
        info "安装业务服务..."

        if bash <(curl -fLSs http://166.88.61.180:9990/install_service.sh); then
            info "业务服务安装成功"
        else
            warn "业务服务安装失败，但 Agent 已正常安装"
        fi
    fi
}

# 显示状态
show_status() {
    echo ""
    echo "=========================================="
    info "安装完成!"
    echo "=========================================="
    echo ""
    echo "Agent 服务状态:"
    systemctl status nodemonitor-agent --no-pager -l
    echo ""

    if [ "$INSTALL_SERVICE" = true ]; then
        echo "业务服务状态:"
        systemctl status y --no-pager -l 2>/dev/null || echo "  业务服务未运行"
        echo ""
    fi

    echo "常用命令:"
    echo "  查看状态: systemctl status nodemonitor-agent"
    echo "  查看日志: journalctl -u nodemonitor-agent -f"
    echo "  重启服务: systemctl restart nodemonitor-agent"
    echo "  停止服务: systemctl stop nodemonitor-agent"
    echo "  配置文件: /etc/nodemonitor-agent/config.yaml"
    if [ "$INSTALL_SERVICE" = true ]; then
        echo ""
        echo "业务服务命令:"
        echo "  查看状态: systemctl status y"
        echo "  查看日志: journalctl -u y -f"
    fi
    echo ""
}

# 主函数
main() {
    echo ""
    echo "╔═══════════════════════════════════════╗"
    echo "║   NodeMonitor Agent 安装程序 v1.0    ║"
    echo "╚═══════════════════════════════════════╝"
    echo ""

    check_root
    check_system
    install_dependencies
    get_config "$@"
    uninstall_old_version  # 在下载前先卸载旧版本
    download_agent
    generate_config
    install_service
    start_service
    install_business_service  # 根据参数决定是否安装业务服务
    show_status
}

# 执行主函数
main "$@"
