#!/bin/bash
# ================================================================
# Nexus Shell Agent — 心跳 + 健康接口
# 依赖: bash, curl
# ================================================================
HEARTBEAT_INTERVAL="${HEARTBEAT_INTERVAL:-60}"
LOG_FILE="${LOG_FILE:-/var/log/nexus-agent.log}"
CENTRAL_URL="${CENTRAL_URL:-}"
CENTRAL_API_KEY="${CENTRAL_API_KEY:-}"
SERVER_ID="${SERVER_ID:-0}"
AGENT_PORT="${AGENT_PORT:-8601}"

log() {
    local ts=$(date '+%Y-%m-%d %H:%M:%S')
    echo "${ts} [$1] $2" >> "$LOG_FILE" 2>/dev/null
    echo "${ts} [$1] $2"
}

check_deps() {
    if ! command -v curl >/dev/null 2>&1; then
        log "ERROR" "缺少 curl，请安装: apt install curl"
        exit 1
    fi
}

get_system_info() {
    local hn=$(hostname 2>/dev/null)
    local load=$(awk '{print $1}' /proc/loadavg 2>/dev/null)
    local mem_total=$(awk '/Mem:/{print $2}' /proc/meminfo 2>/dev/null)
    local mem_avail=$(awk '/MemAvailable:/{print $2}' /proc/meminfo 2>/dev/null)
    local disk_pct=$(df / 2>/dev/null | awk 'NR==2{print $5}' | tr -d '%')
    echo "{\"hostname\":\"${hn}\",\"load\":\"${load}\",\"mem_kb\":${mem_total:-0},\"mem_avail_kb\":${mem_avail:-0},\"disk_pct\":${disk_pct:-0}}"
}

heartbeat_loop() {
    while true; do
        local info=$(get_system_info)
        curl -s -o /dev/null -X POST -H "Content-Type: application/json" \
            -H "X-API-Key: ${CENTRAL_API_KEY}" \
            -d "{\"server_id\":${SERVER_ID},\"is_online\":true,\"system_info\":${info}}" \
            "${CENTRAL_URL}/api/agent/heartbeat" 2>/dev/null
        if [ $? -eq 0 ]; then
            log "INFO" "心跳 OK"
        else
            log "WARN" "心跳失败: ${CENTRAL_URL}"
        fi
        sleep "$HEARTBEAT_INTERVAL"
    done
}

health_server() {
    while true; do
        if command -v nc >/dev/null 2>&1; then
            printf "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"status\":\"healthy\",\"agent\":\"nexus-shell\"}" \
                | nc -l -p "${AGENT_PORT}" -q 1 2>/dev/null
        else
            exec 3<>/dev/tcp/0.0.0.0/${AGENT_PORT} 2>/dev/null && {
                printf "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"status\":\"healthy\"}" >&3
                exec 3>&-
            } || sleep 1
        fi
    done
}

cleanup() {
    log "INFO" "正在停止..."
    for pid in "${PIDS[@]}"; do kill "$pid" 2>/dev/null; done
}
trap cleanup SIGINT SIGTERM

main() {
    echo "=========================================="
    echo "  Nexus Shell Agent — 心跳上报"
    echo "=========================================="
    check_deps
    log "INFO" "中央服务器: ${CENTRAL_URL}"
    log "INFO" "服务器ID: ${SERVER_ID}"
    log "INFO" "心跳间隔: ${HEARTBEAT_INTERVAL}秒"

    heartbeat_loop &
    PIDS+=($!)
    log "INFO" "心跳服务已启动"

    health_server &
    PIDS+=($!)
    log "INFO" "健康接口: http://0.0.0.0:${AGENT_PORT}/health"

    log "INFO" "Agent 已启动，按 Ctrl+C 停止"
    wait
}

case "${1:-}" in
    stop)     systemctl stop nexus-agent; echo "已停止" ;;
    restart)  systemctl restart nexus-agent; echo "已重启" ;;
    status)   systemctl status nexus-agent --no-pager 2>/dev/null || echo "未运行" ;;
    log|logs) journalctl -u nexus-agent -f --no-pager ;;
    *)        main ;;
esac
