#!/usr/bin/env bash
# setup_ingress.sh — run this ON THE HOST (where you have kubectl), NOT in the pod.
# Wires podcast.tobiasweissert.ch -> the openclaw gateway pod's feed server (:8899)
# via a k8s Service + Traefik Ingress with an automatic cert-manager TLS cert.
#
# Safe to re-run (kubectl apply is idempotent).
set -euo pipefail

NS=openclaw
HOST=podcast.tobiasweissert.ch
TARGET_PORT=8899

echo "==> Namespace: $NS   Host: $HOST"

# 1) Reuse the exact selector that already targets the gateway pod.
SEL_JSON=$(kubectl -n "$NS" get svc openclaw -o jsonpath='{.spec.selector}')
echo "==> Gateway pod selector: $SEL_JSON"
[ "$SEL_JSON" = "{}" ] || [ -z "$SEL_JSON" ] && { echo "!! Could not read selector from svc/openclaw"; exit 1; }

# 2) Pick a cert-manager ClusterIssuer (prefer a production Let's Encrypt one).
ISSUER=$(kubectl get clusterissuer -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null | grep -iE 'prod|letsencrypt' | grep -iv staging | head -1 || true)
[ -z "$ISSUER" ] && ISSUER=$(kubectl get clusterissuer -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [ -z "$ISSUER" ]; then
  echo "!! No ClusterIssuer found. Create a Let's Encrypt ClusterIssuer first, then re-run."
  exit 1
fi
echo "==> Using ClusterIssuer: $ISSUER"

# 3) Apply Service + Ingress as one JSON document (selector injected as-is).
cat <<EOF | kubectl -n "$NS" apply -f -
{
  "apiVersion": "v1",
  "kind": "List",
  "items": [
    {
      "apiVersion": "v1",
      "kind": "Service",
      "metadata": { "name": "podcast-feed" },
      "spec": {
        "selector": $SEL_JSON,
        "ports": [ { "name": "http", "port": 80, "targetPort": $TARGET_PORT } ]
      }
    },
    {
      "apiVersion": "networking.k8s.io/v1",
      "kind": "Ingress",
      "metadata": {
        "name": "podcast-feed",
        "annotations": {
          "cert-manager.io/cluster-issuer": "$ISSUER",
          "traefik.ingress.kubernetes.io/router.entrypoints": "websecure,web"
        }
      },
      "spec": {
        "ingressClassName": "traefik",
        "rules": [ {
          "host": "$HOST",
          "http": { "paths": [ {
            "path": "/",
            "pathType": "Prefix",
            "backend": { "service": { "name": "podcast-feed", "port": { "number": 80 } } }
          } ] }
        } ],
        "tls": [ { "hosts": [ "$HOST" ], "secretName": "podcast-feed-tls" } ]
      }
    }
  ]
}
EOF

echo
echo "==> Applied. Waiting for the TLS certificate to be issued (cert-manager, HTTP-01)…"
kubectl -n "$NS" wait --for=condition=Ready certificate/podcast-feed-tls --timeout=120s || \
  echo "   (cert not Ready yet — check: kubectl -n $NS describe certificate podcast-feed-tls)"

echo
echo "==> Done. Test with:"
echo "    curl -I https://$HOST/feed.xml"
