#!/usr/bin/env bash
# deploy_feed.sh — run ON THE HOST (needs kubectl). Durable version.
#
# Serves podcast.tobiasweissert.ch from a dedicated, self-healing nginx
# Deployment that mounts the SAME persistent data volume as the openclaw
# gateway pod (read-only), so it does NOT depend on any process inside the
# gateway pod. k8s keeps it running across restarts automatically.
#
# Creates: Deployment + Service + Ingress (Traefik) + cert-manager TLS cert.
# Idempotent — safe to re-run.
set -euo pipefail

NS=openclaw
HOST=podcast.tobiasweissert.ch
DATA_MOUNT=/home/node/.openclaw          # mountPath inside the gateway pod
SUBPATH=workspace/podcast                # podcast dir relative to the volume root

echo "==> Locating the gateway deployment and its data volume in ns/$NS ..."
DJSON=$(kubectl -n "$NS" get deploy -o json)

{ read -r DEPLOY; read -r VOLJSON; } < <(printf '%s' "$DJSON" | python3 - "$DATA_MOUNT" <<'PY'
import sys, json
data_mount = sys.argv[1]
d = json.load(sys.stdin)
for item in d["items"]:
    spec = item["spec"]["template"]["spec"]
    for c in spec.get("containers", []):
        for m in c.get("volumeMounts", []):
            if m.get("mountPath") == data_mount:
                vol = next(v for v in spec["volumes"] if v["name"] == m["name"])
                vol = {k: v for k, v in vol.items() if k != "name"}   # keep source only
                print(item["metadata"]["name"])
                print(json.dumps(vol))
                sys.exit(0)
sys.exit("!! No deployment mounts %s" % data_mount)
PY
)

echo "    gateway deployment: $DEPLOY"
echo "    data volume source: $VOLJSON"

echo "==> Detecting cert-manager ClusterIssuer ..."
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}')
echo "    issuer: $ISSUER"

echo "==> Applying Deployment + Service + Ingress ..."
python3 - "$HOST" "$SUBPATH" "$ISSUER" "$VOLJSON" <<'PY' | kubectl -n "$NS" apply -f -
import sys, json
host, subpath, issuer, voljson = sys.argv[1:5]
vol = json.loads(voljson)
vol["name"] = "data"
manifest = {
 "apiVersion":"v1","kind":"List","items":[
  {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"name":"podcast-feed"},
   "spec":{"replicas":1,"selector":{"matchLabels":{"app":"podcast-feed"}},
    "template":{"metadata":{"labels":{"app":"podcast-feed"}},
     "spec":{"volumes":[vol],
      "containers":[{"name":"nginx","image":"nginx:alpine",
        "ports":[{"containerPort":80}],
        "volumeMounts":[{"name":"data","mountPath":"/usr/share/nginx/html",
          "subPath":subpath,"readOnly":True}]}]}}}},
  {"apiVersion":"v1","kind":"Service","metadata":{"name":"podcast-feed"},
   "spec":{"selector":{"app":"podcast-feed"},
    "ports":[{"name":"http","port":80,"targetPort":80}]}},
  {"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"}]}}
 ]}
print(json.dumps(manifest))
PY

echo "==> Waiting for TLS certificate (cert-manager, HTTP-01) ..."
kubectl -n "$NS" wait --for=condition=Ready certificate/podcast-feed-tls --timeout=150s || \
  kubectl -n "$NS" describe certificate podcast-feed-tls || true

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