#!/bin/bash
# 健康檢查 API - 由 Nginx fcgiwrap 執行
# 用法: /api/health?service=<service_name>

# 設定 HTTP headers
echo "Content-Type: application/json"
echo "Access-Control-Allow-Origin: *"
echo "Access-Control-Allow-Methods: GET"
echo "Cache-Control: no-cache"
echo ""

# 解析查詢參數
SERVICE=$(echo "$QUERY_STRING" | sed -n 's/.*service=\([^&]*\).*/\1/p')

# 定義服務健康檢查 URL
declare -A HEALTH_URLS=(
    ["momo-live"]="https://mo.wooo.work/health"
    ["momo-prod"]="https://mo.wooo.work/health"
    ["gitlab"]="http://127.0.0.1:8929/"
    ["registry"]="http://127.0.0.1:5002/v2/"
    ["n8n"]="http://127.0.0.1:5678/"
    ["grafana"]="http://127.0.0.1:30030/"
    ["prometheus"]="http://10.43.25.78:9090/-/healthy"
    ["alertmanager"]="http://10.43.79.187:9093/-/healthy"
    ["superset"]="http://127.0.0.1:8088/health"
    ["metabase"]="http://127.0.0.1:3030/api/health"
)

# 檢查服務
if [[ -z "$SERVICE" ]]; then
    # 返回所有服務狀態
    echo '{"services": {'
    first=true
    for svc in "${!HEALTH_URLS[@]}"; do
        url="${HEALTH_URLS[$svc]}"
        start_time=$(date +%s%3N)
        response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 10 "$url" 2>/dev/null)
        end_time=$(date +%s%3N)
        response_time=$((end_time - start_time))

        if [[ "$response" == "200" ]] || [[ "$response" == "302" ]] || [[ "$response" == "401" ]]; then
            status="online"
        else
            status="offline"
        fi

        if [ "$first" = true ]; then
            first=false
        else
            echo ","
        fi
        echo -n "\"$svc\": {\"status\": \"$status\", \"code\": $response, \"responseTime\": $response_time}"
    done
    echo '}}'
else
    # 返回單個服務狀態
    url="${HEALTH_URLS[$SERVICE]}"
    if [[ -z "$url" ]]; then
        echo '{"error": "Unknown service", "service": "'"$SERVICE"'"}'
        exit 0
    fi

    start_time=$(date +%s%3N)
    response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 --max-time 10 "$url" 2>/dev/null)
    end_time=$(date +%s%3N)
    response_time=$((end_time - start_time))

    if [[ "$response" == "200" ]] || [[ "$response" == "302" ]] || [[ "$response" == "401" ]]; then
        status="online"
    else
        status="offline"
    fi

    echo "{\"service\": \"$SERVICE\", \"status\": \"$status\", \"code\": $response, \"responseTime\": $response_time}"
fi
