#!/bin/bash
# Connectivity check for observability dependencies of our agent runtime.
OUT=/opt/data/workspace/i25945/obs
mkdir -p "$OUT"
: > "$OUT/dns.txt"; : > "$OUT/tcp.txt"; : > "$OUT/http.txt"
echo "== related env var names (names only) ==" > "$OUT/envnames.txt"
env | cut -d= -f1 | grep -Ei 'lang|otel|otlp|trace|grafana|clickhouse|jaeger|prom|sentry|posthog' | sort >> "$OUT/envnames.txt"
if [ -f /opt/data/.env ]; then cut -d= -f1 /opt/data/.env | grep -Ei 'lang|otel|otlp|trace|grafana|clickhouse|jaeger|prom|sentry' | sort | sed 's/^/dotenv:/' >> "$OUT/envnames.txt"; fi
NS="agentek monitoring observability langfuse agentek-system default"
SVC="langfuse langfuse-web langfuse-server langfuse-worker clickhouse otel otel-collector otel-collector-collector opentelemetry-collector grafana prometheus prometheus-server tempo jaeger console-backend litellm-gateway postgresql redis"
for ns in $NS; do for s in $SVC; do h="$s.$ns.svc.cluster.local"; ip=$(getent hosts "$h" 2>/dev/null | awk '{print $1}' | head -1); [ -n "$ip" ] && echo "$h $ip" >> "$OUT/dns.txt"; done; done
while read -r h ip; do
  for p in 3000 3001 80 8080 8000 4317 4318 9090 3100 16686 5432 6379 4000; do
    (timeout 2 bash -c "echo > /dev/tcp/$h/$p") 2>/dev/null && echo "OPEN $h:$p" >> "$OUT/tcp.txt"
  done
done < "$OUT/dns.txt"
hget(){ name=$1; url=$2; code=$(curl -sk -m 6 -o "$OUT/$name.out" -w '%{http_code}' "$url"); echo "$url -> $code $(wc -c < "$OUT/$name.out")B" >> "$OUT/http.txt"; }
hget lf_ing_health "https://langfuse.k.agentek.ru/api/public/health"
hget lf_ing_traces "https://langfuse.k.agentek.ru/api/public/traces?limit=1"
hget otel_ing_root "https://otel.k.agentek.ru/"
hget graf_ing_health "https://grafana.k.agentek.ru/api/health"
while read -r h ip; do
  case "$h" in
    langfuse*|*clickhouse*) hget "int_${h}_health" "http://$h:3000/api/public/health" ;;
    otel*) hget "int_${h}_4318" "http://$h:4318/v1/traces" ;;
    grafana*) hget "int_${h}_health" "http://$h:3000/api/health" ;;
  esac
done < "$OUT/dns.txt"
echo DONE > "$OUT/done"
