name: Deploy

# Phase 4 of the GitOps refactor (2026-04-20). Deploy is now driven by
# GitHub Actions rather than the vibecarbon CLI applying manifests from a
# local workstation. This keeps:
#
#   • Secrets in GitHub Environments (never committed, env-scoped).
#   • Source of truth in the repo under k8s/.
#   • Reconciliation via Flux (the cluster's own GitRepository +
#     Kustomization watches the repo's main branch every minute).
#
# The CLI still creates the cluster (Pulumi) and bootstraps the first
# workflow run — thereafter, `git push` is the deploy verb.
#
# Security note: all external-input interpolation flows through the
# `env:` block rather than inline `${{ }}` in `run:` blocks, to avoid the
# script-injection class of workflow CVEs. Secrets are written to files
# via base64 when possible (kubeconfig) to avoid shell quoting hazards.

on:
  # No `push` trigger: this workflow requires a per-environment KUBECONFIG_B64
  # secret which only exists after `vibecarbon deploy --k8s` has seeded the
  # matching GitHub Environment. A `push` trigger would fail fast (kubectl
  # connection refused) for every deploy, whether k8s or compose-only. The
  # vibecarbon CLI invokes this workflow explicitly via the gh CLI
  # (triggerDeployWorkflow in gitops-deploy.js) with the right environment,
  # so manual dispatch is the only entry point.
  workflow_dispatch:
    inputs:
      environment:
        description: 'Environment to deploy (dev / staging / prod)'
        type: environment
        required: true

concurrency:
  # Serialize per-environment so two pushes don't race against Flux's
  # reconcile loop.
  group: deploy-${{ inputs.environment || 'prod' }}
  cancel-in-progress: false

permissions:
  contents: read
  id-token: write  # for future OIDC to cloud providers; not used today

jobs:
  apply-secrets:
    # Reads env-specific secrets from GitHub Environments and applies them
    # to the cluster as the `vibecarbon-app-secrets` and
    # `vibecarbon-infra-secrets` Secrets. Flux does NOT manage them (no
    # manifest in k8s/) so there's no drift.
    name: Apply env secrets → cluster
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment || 'prod' }}
    env:
      KUBECONFIG: ${{ github.workspace }}/kubeconfig
    steps:
      - uses: actions/checkout@v4

      - name: Install kubectl
        uses: azure/setup-kubectl@v4
        with:
          # Pin to a specific minor; bump deliberately.
          version: 'v1.37.2'

      - name: Write kubeconfig from env secret
        env:
          KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
        run: |
          printf '%s' "$KUBECONFIG_B64" | base64 -d > "$KUBECONFIG"
          chmod 600 "$KUBECONFIG"
          # Response compression off for every cluster entry: gzip on the API's
          # large responses (the OpenAPI documents kubectl downloads before an
          # apply) cost seconds per call from a distant runner. A kubeconfig the
          # CLI uploads already carries the field; an older upload gets it here.
          for cluster in $(kubectl config get-clusters | tail -n +2); do
            kubectl config set "clusters.${cluster}.disable-compression" true >/dev/null
          done
          kubectl version --client=true

      - name: Ensure vibecarbon namespace exists
        run: kubectl create namespace vibecarbon --dry-run=client -o yaml | kubectl apply -f -

      # The backup CronJob and its retention ConfigMap are per environment, but
      # the committed k8s/base is shared by every environment Flux reconciles
      # from this branch, so Flux's vibecarbon-base drops the CronJob
      # (k8s/flux/clusters/*) and this step owns both. The values are the
      # GitHub Environment vars `vibecarbon configure cicd` seeds from the
      # environment's backup config. The same renderer the CLI deploy uses
      # (scripts/render-backup-settings.mjs) fills in the CronJob schedule and
      # writes the vibecarbon-backup-settings ConfigMap; it refuses to run
      # with either var unset. Rendered to a file first: the default `run`
      # shell has no pipefail, so a failed render must not reach kubectl.
      - name: Render and apply the backup CronJob and settings (deploy-owned, not Flux)
        env:
          BACKUP_SCHEDULE: ${{ vars.BACKUP_SCHEDULE }}
          BACKUP_RETENTION_DAYS: ${{ vars.BACKUP_RETENTION_DAYS }}
          # The CronJob's kubectl, from the environment's version set.
          KUBECTL_IMAGE: ${{ vars.KUBECTL_IMAGE }}
          # Optional: where the CronJob saves the TLS certificate (seeded by
          # `vibecarbon configure cicd` when the env has a backup bucket).
          TLS_SNAPSHOT_S3_PREFIX: ${{ vars.TLS_SNAPSHOT_S3_PREFIX }}
        run: |
          node scripts/render-backup-settings.mjs k8s/base > "$RUNNER_TEMP/backup.yaml"
          kubectl apply --namespace=vibecarbon --server-side --force-conflicts \
            --field-manager=github-actions-deploy -f "$RUNNER_TEMP/backup.yaml"

      # Apply the app's Secret (vibecarbon-app-secrets) and the infra Secret
      # (vibecarbon-infra-secrets). Server-side apply with a distinct field
      # manager ensures Flux doesn't try to prune these fields later, and that
      # rotations simply overwrite.
      #
      # Both Secrets are built from ALL environment+repo secrets
      # (`toJSON(secrets)`), each by a positive list, so a secret seeded for
      # some other purpose never lands in a pod by default:
      #   - APP_KEYS: the app's runtime keys (APP_RUNTIME_KEYS and
      #     APP_RUNTIME_EXTRA_KEYS in src/lib/deploy/app-runtime-env.js). The
      #     app envFrom's this Secret whole. SITE_URL comes from vars instead.
      #   - INFRA_KEYS: the infra passwords (INFRA_SECRET_KEYS in
      #     src/lib/deploy/k8s/k3s.js), read by the db and add-on pods by key.
      #   - the del() list, defence in depth: CI and every cloud/DNS token the
      #     CLI can seed, which have their own Secrets or none.
      # A new configure-managed key joins APP_KEYS here. All three lists are
      # census-pinned to their sources by
      # tests/unit/deploy/deploy-workflow-secret-sync.test.ts, which fails
      # until this file matches.
      # `toJSON(secrets)` is bound to an env var (not interpolated inline in
      # the script) for defense-in-depth; kubectl --from-literal passes values
      # through argv with no shell interpretation.
      - name: Apply vibecarbon-app-secrets and vibecarbon-infra-secrets
        env:
          ALL_SECRETS: ${{ toJSON(secrets) }}
          SITE_URL: ${{ vars.SITE_URL }}
        run: |
          APP_KEYS='[
            "BETTER_AUTH_SECRET","APP_DB_PASSWORD","ADMIN_EMAIL","ADMIN_PASSWORD","SITE_URL",
            "CORS_ORIGINS","MAGIC_LINK_ENABLED","TRUSTED_PROXY_HOPS",
            "PROJECT_NAME","REDIS_ENABLED","N8N_ENABLED",
            "METABASE_ENABLED","OBSERVABILITY_ENABLED",
            "VITE_PLAUSIBLE_DOMAIN","VITE_PLAUSIBLE_SCRIPT_URL",
            "STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","PADDLE_API_KEY",
            "PADDLE_WEBHOOK_SECRET","POLAR_ACCESS_TOKEN",
            "POLAR_WEBHOOK_SECRET","GOOGLE_CLIENT_SECRET",
            "MICROSOFT_CLIENT_SECRET","SMTP_PASS","BILLING_PROVIDER",
            "STRIPE_PRICE_STARTER","STRIPE_PRICE_PRO","PADDLE_ENVIRONMENT",
            "PADDLE_PRICE_STARTER","PADDLE_PRICE_PRO","POLAR_ORGANIZATION_ID",
            "POLAR_PRICE_STARTER","POLAR_PRICE_PRO","GOOGLE_ENABLED",
            "GOOGLE_CLIENT_ID","MICROSOFT_ENABLED","MICROSOFT_CLIENT_ID",
            "MICROSOFT_TENANT_ID","SMTP_HOST","SMTP_PORT","SMTP_USER",
            "SMTP_ADMIN_EMAIL","SMTP_SENDER_NAME","ACME_CA_SERVER",
            "ALLOWED_SSH_IPS","S3_ACCESS_KEY","S3_SECRET_KEY","S3_BUCKET",
            "S3_ENDPOINT","S3_REGION","REDIS_URL"
          ]'
          INFRA_KEYS='["DB_PASSWORD","REPL_PASSWORD","METABASE_DB_PASSWORD","N8N_DB_PASSWORD","N8N_ENCRYPTION_KEY"]'
          secret_args() {
            printf '%s' "$ALL_SECRETS" | jq -r --argjson app "$APP_KEYS" --argjson infra "$INFRA_KEYS" --arg want "$1" '
              del(
                .KUBECONFIG_B64,
                .GITHUB_TOKEN, .github_token,
                .HETZNER_API_TOKEN, .HCLOUD_TOKEN,
                .CLOUDFLARE_API_TOKEN,
                .DIGITALOCEAN_API_TOKEN, .DIGITALOCEAN_TOKEN,
                .LINODE_API_TOKEN, .LINODE_TOKEN,
                .VULTR_API_TOKEN, .VULTR_API_KEY,
                .SCALEWAY_SECRET_KEY, .SCW_SECRET_KEY,
                .VIBECARBON_STATE_PASSPHRASE
              )
              | to_entries[]
              | select(.value != null and .value != "")
              | select(.key as $k
                  | if $want == "infra" then ($infra | index($k)) != null
                    else ($app | index($k)) != null and $k != "SITE_URL" end)
              | "--from-literal=\(.key)=\(.value)"'
          }
          mapfile -t APP_ARGS < <(secret_args app)
          mapfile -t INFRA_ARGS < <(secret_args infra)
          kubectl create secret generic vibecarbon-app-secrets \
            --namespace=vibecarbon \
            --from-literal=SITE_URL="$SITE_URL" \
            "${APP_ARGS[@]}" \
            --dry-run=client -o yaml \
          | kubectl apply --server-side --force-conflicts \
              --field-manager=github-actions-deploy -f -
          kubectl create secret generic vibecarbon-infra-secrets \
            --namespace=vibecarbon \
            "${INFRA_ARGS[@]}" \
            --dry-run=client -o yaml \
          | kubectl apply --server-side --force-conflicts \
              --field-manager=github-actions-deploy -f -

      # No cloud provider Secret here: `vibecarbon deploy` hands the provider
      # API token to the cluster itself on every deploy (kube-system/hcloud,
      # digitalocean or linode), so GitHub keeps no copy of it.

  bootstrap-flux:
    # Phase 4.3b.C of the GitOps refactor: idempotently install Flux +
    # the flux-system Secret (Git auth) + the root GitRepository and
    # Kustomizations that watch the customer's repo. Runs every deploy
    # (safe — kubectl apply --server-side is a no-op when state matches).
    #
    # After this job succeeds, Flux is in charge of reconciling k8s/base/
    # from the main branch. The apply-secrets job is what keeps the
    # per-env app and infra Secrets in sync with GitHub Environment
    # secrets.
    name: Bootstrap Flux + root Kustomization
    needs: apply-secrets
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment || 'prod' }}
    env:
      KUBECONFIG: ${{ github.workspace }}/kubeconfig
    steps:
      - uses: actions/checkout@v4

      - name: Install kubectl
        uses: azure/setup-kubectl@v4
        with:
          version: 'v1.37.2'

      - name: Write kubeconfig from env secret
        env:
          KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
        run: |
          printf '%s' "$KUBECONFIG_B64" | base64 -d > "$KUBECONFIG"
          chmod 600 "$KUBECONFIG"
          # Response compression off for every cluster entry: gzip on the API's
          # large responses (the OpenAPI documents kubectl downloads before an
          # apply) cost seconds per call from a distant runner. A kubeconfig the
          # CLI uploads already carries the field; an older upload gets it here.
          for cluster in $(kubectl config get-clusters | tail -n +2); do
            kubectl config set "clusters.${cluster}.disable-compression" true >/dev/null
          done

      - name: Install Flux if not present
        # FLUX_INSTALL_URL matches src/lib/deploy/k8s/index.js so the
        # imperative path and GitOps path land on the same Flux version.
        # Bumping here requires a matching bump there + a re-test.
        run: |
          if ! kubectl -n flux-system get deployment source-controller > /dev/null 2>&1; then
            kubectl apply -f https://github.com/fluxcd/flux2/releases/download/v2.10.0/install.yaml
            kubectl -n flux-system wait --for=condition=available \
              deployment/source-controller deployment/kustomize-controller \
              deployment/helm-controller deployment/notification-controller \
              --timeout=5m
          fi

      # cert-manager + Traefik CRDs must be installed BEFORE the root
      # Kustomization reconciles. k8s/base/traefik/ contains IngressRoute
      # (traefik.io/v1alpha1) and Certificate (cert-manager.io/v1)
      # resources; Flux's vibecarbon-base Kustomization will sit with
      # "Ready=False: resource mapping not found" forever without the
      # CRDs installed out-of-band.
      #
      # Under the pre-GitOps flow these were installed imperatively by
      # applyKubernetesManifests before Flux was bootstrapped (see
      # src/lib/deploy/k8s/index.js and the CERT_MANAGER_INSTALL_URL
      # constant). The GitOps refactor moved Flux bootstrap here but
      # left this step out — e2e run 2026-04-22 18:29 UTC showed
      # vibecarbon-base timing out after 10m on exactly this.
      #
      # cert-manager is the same ONE rendered apply the CLI deploy makes
      # (scripts/render-cert-manager.mjs holds the version, the controller
      # flags and the control-plane pin). Applying the bare upstream manifest
      # here would strip the flags and the pin the CLI rendered in, and roll
      # the controller on every run; the rendered one re-applies as a no-op.
      #
      # The CRD URL carries the Traefik tag of the environment's version set
      # (TRAEFIK_VERSION, seeded by `vibecarbon configure cicd`): a CRD behind
      # the running Traefik prunes newer fields without an error.
      - name: Install cert-manager + Traefik CRDs
        env:
          TRAEFIK_VERSION: ${{ vars.TRAEFIK_VERSION }}
        run: |
          [[ "$TRAEFIK_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || {
            echo "::error::TRAEFIK_VERSION is not set for this environment. Run vibecarbon configure cicd <env>."
            exit 1
          }
          node scripts/render-cert-manager.mjs "$RUNNER_TEMP/cert-manager"
          kubectl apply -k "$RUNNER_TEMP/cert-manager"
          mkdir -p "$RUNNER_TEMP/traefik-crds"
          sed "s/{{TRAEFIK_VERSION}}/$TRAEFIK_VERSION/g" k8s/infra/traefik-crds/kustomization.yaml \
            > "$RUNNER_TEMP/traefik-crds/kustomization.yaml"
          kubectl apply -k "$RUNNER_TEMP/traefik-crds"
          kubectl -n cert-manager wait --for=condition=available \
            deployment/cert-manager \
            deployment/cert-manager-webhook \
            deployment/cert-manager-cainjector \
            --timeout=5m

      # The controller SETTLED before the Certificate lands: its rollout
      # complete and its leader lease on a pod of the current ReplicaSet. A
      # handoff while the Certificate lands can miss the Secret it should
      # reuse and issue a new certificate. The same wait the CLI deploy and a
      # failover promotion run; bounded, then one error line.
      - name: Wait for a settled cert-manager leader
        run: bash scripts/await-cert-manager-leader.sh

      # The vibecarbon-tls Certificate is DEPLOY-owned: its names and issuer
      # are per environment, while the committed k8s/base is shared by every
      # environment on the branch, so Flux drops it from its build
      # (k8s/flux/clusters/*) and this step owns it, after the cert-manager
      # CRDs above. The values are the GitHub Environment vars that
      # `vibecarbon configure cicd` seeds; the same renderer the CLI deploy
      # uses (scripts/render-tls-certificate.mjs) validates them and refuses
      # to run with any unset. Rendered to a file first: the default run
      # shell has no pipefail, so a failed render must not reach kubectl.
      # No --force-conflicts: a Certificate the CLI deploy or a failover
      # promotion set differently fails this apply instead of being
      # overwritten, and the error line names the repair: a deploy, or
      # `vibecarbon configure cicd <env>` to re-seed after a role change.
      - name: Render and apply the TLS Certificate (deploy-owned, not Flux)
        env:
          TLS_CERT_ISSUER: ${{ vars.TLS_CERT_ISSUER }}
          TLS_CERT_EFFECTIVE_ISSUER: ${{ vars.TLS_CERT_EFFECTIVE_ISSUER }}
          TLS_CERT_DNS_NAMES: ${{ vars.TLS_CERT_DNS_NAMES }}
        run: |
          node scripts/render-tls-certificate.mjs > "$RUNNER_TEMP/certificate.yaml"
          kubectl apply --server-side --field-manager=github-actions-deploy \
            -f "$RUNNER_TEMP/certificate.yaml" || { echo "::error::the TLS Certificate apply failed (most often a field conflict with a CLI deploy or a failover). Run vibecarbon deploy <env> (or vibecarbon configure cicd <env> if the roles changed), then re-run this workflow"; exit 1; }

      - name: Create flux-system Secret (Git auth for private repo)
        # Flux uses `username`/`password` keys on a namespace Secret to
        # pull the GitRepository. Using the workflow's GITHUB_TOKEN keeps
        # everything within the repo's own perms — no separate PAT to
        # rotate. `x-access-token` is GitHub's convention for short-lived
        # Actions tokens.
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          kubectl create namespace flux-system --dry-run=client -o yaml | kubectl apply -f -
          kubectl create secret generic flux-system \
            --namespace=flux-system \
            --from-literal=username=x-access-token \
            --from-literal=password="$GITHUB_TOKEN" \
            --dry-run=client -o yaml \
          | kubectl apply --server-side --force-conflicts \
              --field-manager=github-actions-deploy -f -

      - name: Apply root GitRepository + Kustomizations
        # Template at carbon/k8s/flux/clusters/primary/vibecarbon.yaml
        # (copied to k8s/flux/clusters/primary/vibecarbon.yaml in the
        # customer repo by `vibecarbon create`). Its GitRepository URL names
        # the real owner and repo once `vibecarbon configure cicd` has run,
        # so by the time Actions runs this file has the real URL. (No
        # create-time tokens in this file: configure installs it as is.)
        run: |
          kubectl apply --server-side --force-conflicts \
            --field-manager=github-actions-deploy \
            -f k8s/flux/clusters/primary/vibecarbon.yaml

  trigger-reconcile:
    # After Secrets are fresh + Flux is bootstrapped, nudge Flux to
    # reconcile now rather than wait up to 10 min for its interval.
    name: Trigger Flux reconcile
    needs: [apply-secrets, bootstrap-flux]
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment || 'prod' }}
    env:
      KUBECONFIG: ${{ github.workspace }}/kubeconfig
    steps:
      - name: Install kubectl
        uses: azure/setup-kubectl@v4
        with:
          version: 'v1.37.2'

      - name: Write kubeconfig from env secret
        env:
          KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
        run: |
          printf '%s' "$KUBECONFIG_B64" | base64 -d > "$KUBECONFIG"
          chmod 600 "$KUBECONFIG"
          # Response compression off for every cluster entry: gzip on the API's
          # large responses (the OpenAPI documents kubectl downloads before an
          # apply) cost seconds per call from a distant runner. A kubeconfig the
          # CLI uploads already carries the field; an older upload gets it here.
          for cluster in $(kubectl config get-clusters | tail -n +2); do
            kubectl config set "clusters.${cluster}.disable-compression" true >/dev/null
          done

      - name: Annotate GitRepository + root Kustomizations
        run: |
          now="$(date -u +%FT%TZ)"
          kubectl -n flux-system annotate --overwrite gitrepository/vibecarbon \
            reconcile.fluxcd.io/requestedAt="$now" || true
          for ks in vibecarbon-base; do
            kubectl -n flux-system annotate --overwrite kustomization/"$ks" \
              reconcile.fluxcd.io/requestedAt="$now" || true
          done

      # State dump is inlined into the SAME shell as the wait commands so
      # its output shows up in `gh run view <id> --log-failed`. A separate
      # `if: failure()` job-step would run but wouldn't be in the failed-
      # step logs (which is what waitForLatestWorkflowRun fetches), so
      # debugging from the operator's machine would still be opaque.
      - name: Wait for reconciliation (10 min budget)
        run: |
          set +e
          kubectl -n flux-system wait --for=condition=Ready kustomization/vibecarbon-base --timeout=10m
          BASE_RC=$?
          if [ $BASE_RC -ne 0 ]; then
            echo "=== RECONCILE FAILED — dumping Flux state ==="
            echo "base=$BASE_RC"
            echo
            echo "=== Flux GitRepository ==="
            kubectl -n flux-system describe gitrepository/vibecarbon || true
            for ks in vibecarbon-base; do
              echo
              echo "=== Kustomization: $ks ==="
              kubectl -n flux-system describe kustomization/"$ks" || true
            done
            echo
            echo "=== Flux events (last 80) ==="
            kubectl -n flux-system get events --sort-by=.lastTimestamp 2>/dev/null | tail -80
            echo
            echo "=== vibecarbon namespace events (last 80) ==="
            kubectl -n vibecarbon get events --sort-by=.lastTimestamp 2>/dev/null | tail -80
            echo
            echo "=== Non-ready pods (all namespaces) ==="
            kubectl get pods -A --field-selector=status.phase!=Running,status.phase!=Succeeded 2>/dev/null
            echo
            echo "=== vibecarbon pods ==="
            kubectl -n vibecarbon get pods -o wide 2>/dev/null
            echo
            echo "=== nodes (internal/external IPs) ==="
            kubectl get nodes -o wide 2>/dev/null
            echo
            echo "=== kube-system pods (CoreDNS + CCM + CSI) ==="
            kubectl -n kube-system get pods -o wide 2>/dev/null
            echo
            echo "=== CoreDNS ConfigMap (upstream resolvers) ==="
            kubectl -n kube-system get configmap coredns -o yaml 2>/dev/null | sed -n '/data:/,/^[^ ]/p' | head -40
            echo
            echo "=== CoreDNS logs (last 30 lines per pod) ==="
            for pod in $(kubectl -n kube-system get pods -l k8s-app=kube-dns -o name 2>/dev/null); do
              echo "--- $pod ---"
              kubectl -n kube-system logs "$pod" --tail=30 2>/dev/null
            done
            echo
            echo "=== Hetzner CCM logs (last 40 lines) ==="
            for pod in $(kubectl -n kube-system get pods -l app.kubernetes.io/name=hcloud-cloud-controller-manager -o name 2>/dev/null); do
              echo "--- $pod ---"
              kubectl -n kube-system logs "$pod" --tail=40 2>/dev/null
            done
            echo
            echo "=== source-controller logs (last 40 lines) ==="
            SC_POD=$(kubectl -n flux-system get pods -l app=source-controller -o name 2>/dev/null | head -1)
            if [ -n "$SC_POD" ]; then
              kubectl -n flux-system logs "$SC_POD" --tail=40 2>/dev/null || true
              kubectl -n flux-system logs "$SC_POD" --previous --tail=40 2>/dev/null || true
            fi
            echo
            echo "=== pod DNS probe (busybox in kube-system) ==="
            # kube-system has relaxed PodSecurity (allows system pods).
            # A plain pod can curl/nslookup without host namespaces —
            # this is what Flux's source-controller is actually doing.
            kubectl -n kube-system run dns-probe-$RANDOM --image=busybox:1.38 \
              --restart=Never --rm -i --timeout=60s \
              --overrides='{"spec":{"containers":[{"name":"probe","image":"busybox:1.38","command":["sh","-c","echo \"--- /etc/resolv.conf ---\"; cat /etc/resolv.conf; echo; echo \"--- nslookup github.com (via coredns) ---\"; nslookup github.com; echo; echo \"--- nslookup github.com @1.1.1.1 ---\"; nslookup github.com 1.1.1.1; echo; echo \"--- wget github.com ---\"; wget -qO- --timeout=5 https://github.com 2>&1 | head -5 || echo wget-failed"]}]}}' \
              2>&1 | head -50 || echo "(pod dns-probe failed)"
            echo
            echo "=== kube-proxy / node routing (kube-proxy pod logs) ==="
            for pod in $(kubectl -n kube-system get pods -l k8s-app=kube-proxy -o name 2>/dev/null | head -1); do
              echo "--- $pod ---"
              kubectl -n kube-system logs "$pod" --tail=20 2>/dev/null
            done
            exit 1
          fi
