#!/bin/bash

# Node Exporter 健康检查脚本
# 输出 JSON 格式结果

set -e

# 检查 Node Exporter 健康状态
check_health() {
    local url="http://localhost:9100"
    local metrics_url="$url/metrics"
    local name="node-exporter"
    local status="unhealth"
    local reason=""
    
    # 检查 curl 是否可用
    if ! command -v curl &> /dev/null; then
        reason="curl 命令不可用，无法进行健康检查"
        echo "{\"name\": \"$name\", \"status\": \"$status\", \"reason\": \"$reason\"}"
        exit 1
    fi
    
    # 测试根路径连接
    local http_code=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000")
    
    if [[ "$http_code" == "200" ]]; then
        # 测试 metrics 端点
        local metrics_code=$(curl -s -o /dev/null -w "%{http_code}" "$metrics_url" 2>/dev/null || echo "000")
        
        if [[ "$metrics_code" == "200" ]]; then
            status="health"
            reason="success"
            echo "{\"name\": \"$name\", \"status\": \"$status\", \"reason\": \"$reason\"}"
            exit 0
        else
            reason="Metrics 端点异常 (HTTP $metrics_code)"
            echo "{\"name\": \"$name\", \"status\": \"$status\", \"reason\": \"$reason\"}"
            exit 1
        fi
    else
        reason="HTTP 服务异常 (HTTP $http_code)，请检查 Node Exporter 是否正在运行在端口 9100"
        echo "{\"name\": \"$name\", \"status\": \"$status\", \"reason\": \"$reason\"}"
        exit 1
    fi
}

# 主函数
main() {
    check_health
}

# 脚本入口
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
