#!/bin/bash
# =============================================================================
# Klyro Edge Installer
# https://get.klyro.security/install.sh
#
# Usage:
#   Production: curl -sfL https://get.klyro.security | sh -s -- <INSTALL_TOKEN>
#   Local:      ./install.sh inst_test --local
#
# Get your install token from: https://app.klyro.security/agents/new
#
# Local Mode (--local):
#   Sets up a complete local environment with:
#   - k3d cluster with local registry
#   - Mock Cloud gRPC server for agent registration
#   - Temporal for workflow orchestration
#   - Agent connected to mock cloud and Temporal
#   - Worker/Operator polling Temporal for tasks
#   - SQLite database for agent state
# =============================================================================
set -e

# sudo's secure_path leaves out /usr/local/bin, where k3s puts k3s and kubectl: without
# it, `sudo sh` misses an installed k3s and --bootstrap installs it again. Appended, so
# it never shadows a command the caller's PATH already finds.
case ":${PATH:-}:" in
    *:/usr/local/bin:*) ;;
    *)
        PATH="${PATH:+$PATH:}/usr/local/bin"
        export PATH
        ;;
esac

KLYRO_API_URL="${KLYRO_API_URL:-}"
NAMESPACE="klyro-system"
RELEASE_NAME="klyro-edge"
MC_RELEASE_NAME="klyro-mc"
MC_DB_EXTERNAL_SECRET="klyro-mc-external-db"
MC_SCIM_TLS_SECRET_DEFAULT="klyro-mc-scim-tls"
MC_VERIFY_TIMEOUT=900
SELF_UPGRADE_TIMEOUT=300
# The k3s that --bootstrap installs, fetched from the environment's Klyro CDN
# (https://<KLYRO_CDN>/k3s/<version>/). .github/workflows/k3s-mirror.yaml reads this
# line and mirrors that version from the k3s GitHub release when it changes.
K3S_VERSION="v1.37.2+k3s1"

# Script and project directories.
# Derived from "$0" (not ${BASH_SOURCE[0]}, a bash array expansion that dash
# rejects at runtime with "Bad substitution") so the script also works when it is
# piped into a POSIX shell: curl -sfL https://get.klyro.security | sh -s -- <TOKEN>.
# In a piped install "$0" is the shell name ("sh"), so dirname yields "." and this
# resolves to the caller's cwd. That is harmless because SCRIPT_DIR/PROJECT_ROOT are
# only consumed by the --local developer path (build_local_images,
# install_helm_chart_local), and install_helm_chart re-derives SCRIPT_DIR from "$0"
# itself. Left unguarded, identical to the derivation in install_helm_chart: on the
# only way this can fail (an unreadable/deleted cwd) it is better to abort loudly via
# set -e than to continue with an empty SCRIPT_DIR and a PROJECT_ROOT of "/..".
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="${SCRIPT_DIR}/.."

# Colors, as the escape characters themselves so plain echo renders them too.
RED=$(printf '\033[0;31m')
GREEN=$(printf '\033[0;32m')
YELLOW=$(printf '\033[0;33m')
BLUE=$(printf '\033[0;34m')
CYAN=$(printf '\033[0;36m')
NC=$(printf '\033[0m')

log_info() { printf "${BLUE}[INFO]${NC} %s\n" "$1"; }
log_success() { printf "${GREEN}[OK]${NC} %s\n" "$1"; }
log_warn() { printf "${YELLOW}[WARN]${NC} %s\n" "$1"; }
log_error() { printf "${RED}[ERROR]${NC} %s\n" "$1" >&2; }
log_step() { printf "${GREEN}>>>${NC} ${BLUE}%s${NC}\n" "$1"; }
log_local() { printf "${CYAN}[LOCAL]${NC} %s\n" "$1"; }

# Spinner for long-running operations
spin() {
    local pid=$1
    local msg=$2
    local spinstr='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
    local i=0
    local rc=0
    printf "${BLUE}[...]${NC} %s " "$msg"
    if [ -t 1 ]; then
        while kill -0 "$pid" 2>/dev/null; do
            i=$(( (i + 1) % 10 ))
            printf "\r${BLUE}[%s]${NC} %s " "$(echo $spinstr | cut -c$((i+1)))" "$msg"
            sleep 0.1
        done
    else
        # No TTY: an in-place redraw becomes a new log line every 0.1s. Poll quietly.
        while kill -0 "$pid" 2>/dev/null; do
            sleep 1
        done
    fi
    # "|| rc=$?" so set -e does not abort before the caller can inspect the status.
    wait "$pid" || rc=$?
    return "$rc"
}

# Wait for a background PID while showing progress, then return its exit status.
#
# On a TTY this animates in place exactly as it always has. With no TTY — CI, SSM,
# `curl … | sh > install.log` — every in-place redraw becomes its own line, which
# floods the log: one 261s helm run produced 439 "[⠋] Deploying Klyro Edge..." lines,
# enough to blow past SSM's output cap and push the real helm error out of the
# captured log entirely (KAN-695). So the non-TTY path prints one static line plus a
# heartbeat every 30s, and polls at 1s so completion is still detected promptly.
#
# Usage:  STATUS=0; spin_wait "$pid" "message" || STATUS=$?
# The message must not contain a '%' (it is passed as a printf argument).
spin_wait() {
    local sw_pid="$1"
    local sw_msg="$2"
    local sw_spinstr='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
    local sw_i=0
    local sw_rc=0
    local sw_elapsed=0

    if [ -t 1 ]; then
        printf "    ${BLUE}[%s]${NC} %s" "$(echo $sw_spinstr | cut -c1)" "$sw_msg"
        while kill -0 "$sw_pid" 2>/dev/null; do
            sw_i=$(( (sw_i + 1) % 10 ))
            printf "\r    ${BLUE}[%s]${NC} %s" "$(echo $sw_spinstr | cut -c$((sw_i+1)))" "$sw_msg"
            sleep 0.1
        done
    else
        printf "    ${BLUE}[...]${NC} %s\n" "$sw_msg"
        while kill -0 "$sw_pid" 2>/dev/null; do
            sleep 1
            sw_elapsed=$((sw_elapsed + 1))
            if [ "$((sw_elapsed % 30))" -eq 0 ]; then
                printf "    ${BLUE}[...]${NC} %s (%ss elapsed)\n" "$sw_msg" "$sw_elapsed"
            fi
        done
    fi

    # "|| sw_rc=$?" so set -e does not abort before the caller can inspect the status.
    wait "$sw_pid" || sw_rc=$?
    return "$sw_rc"
}

# Run command with spinner
run_with_spinner() {
    local msg="$1"
    shift
    if [ "${KLYRO_DEBUG:-}" = "true" ]; then
        printf "${BLUE}[...]${NC} %s\n" "$msg"
        "$@"
        return $?
    else
        "$@" >/dev/null 2>&1 &
        local pid=$!
        spin $pid "$msg"
        local status=$?
        if [ $status -eq 0 ]; then
            printf "\r${GREEN}[OK]${NC} %s    \n" "$msg"
        else
            printf "\r${RED}[FAIL]${NC} %s    \n" "$msg"
        fi
        return $status
    fi
}

show_banner() {
    echo ""
    printf "${BLUE}╔═══════════════════════════════════════════════════════════════╗${NC}\n"
    printf "${BLUE}║${NC}   ${GREEN}Klyro Edge Agent Installer${NC}                                ${BLUE}║${NC}\n"
    printf "${BLUE}║${NC}   AI-powered identity provisioning for Kubernetes            ${BLUE}║${NC}\n"
    printf "${BLUE}╚═══════════════════════════════════════════════════════════════╝${NC}\n"
    echo ""
}

usage() {
    cat <<EOF
Klyro Edge Installer

Usage:
  Production:  curl -sfL https://get.klyro.security | sh -s -- <INSTALL_TOKEN>
  Staging:     curl -sfL https://get.klyro.security | sh -s -- --env staging <INSTALL_TOKEN>
  Dev:         curl -sfL https://get.klyro.security | sh -s -- --env dev <INSTALL_TOKEN>
  Reinstall:   curl -sfL https://get.klyro.security | sh -s -- --reinstall
  Preflight:   curl -sfL https://get.klyro.security | sh -s -- --preflight [<INSTALL_TOKEN>]
  Local:       ./install.sh <TOKEN> --local
  Local+Cloud: ./install.sh <TOKEN> --local --grpc-endpoint grpc.klyro.security:443

Arguments:
  INSTALL_TOKEN       Your one-time install token from the Klyro dashboard
  --env <env>         Target environment: dev, staging, or production (default)
  --local             Enable full local mode with mock cloud, Temporal, etc.
  --with-temporal     Deploy Temporal alongside the agent (for E2E testing)
  --bootstrap         Auto-install a k3s cluster if none is reachable, and deploy
                      the chart via k3s's built-in Helm controller. Reduces the
                      prerequisites to just curl + sh (k3s bundles kubectl + Helm).
                      Alias: --with-k3s
  --data-dir <path>   With --bootstrap: the k3s data dir (images and local-path
                      volumes), default /var/lib/rancher/k3s. Use it to put k3s
                      on a bigger disk. Unsupported under SELinux enforcing.
  --skip-disk-check   Install even when the disk preflight fails (below 30 GiB
                      free or 5% free inodes on the k3s data dir)
  --grpc-endpoint     Custom gRPC endpoint (skips mock cloud setup)
  --api-endpoint      Custom API endpoint (optional, used with --grpc-endpoint)

Components:
  --product <list>    What to install: a comma-separated list of researcher,
                      mc and cli (the klyro CLI, below), or both (researcher,mc,
                      no CLI). Default researcher,mc,cli, MC on the bundled
                      database. --local and --reinstall install the Researcher
                      only. One install token covers the Researcher and MC.
                      The default installs the Researcher only, with a warning,
                      when Klyro Cloud has no MC chart registered (not when
                      --mc-database or --mc-database-url-file is given).
                      --product cli installs only the klyro CLI: no token is
                      needed or redeemed, no cluster is touched, and
                      --bootstrap does nothing.
  --mc-database <m>   MC database: bundled (PostgreSQL on a persistent volume, the
                      default) or external (your PostgreSQL, see below)
  --mc-database-url-file <path>
                      File holding the external PostgreSQL URL
                      (postgres://user:password@host:5432/db?sslmode=require).
                      Implies --mc-database external. Without it, a terminal
                      install asks for the URL. The URL's user must be able to
                      create and alter tables in its default schema: the MC
                      applies its own migrations at startup.
  --mc-chart-version <v>
                      MC chart version to install when Klyro Cloud has none
                      registered for this environment

klyro CLI (cli in --product, the default):
  An install run as root (sudo bash) installs the klyro CLI, with rootless
  Docker, for the user who ran sudo: it prepares the host for that user
  (fapolicyd rule, /etc/subuid and /etc/subgid ranges, loginctl
  enable-linger), then runs https://<cdn>/squad/install.sh as that user.
  With no such user (root without sudo, or not root) the default skips it
  with a warning; an explicit cli in --product stops the install instead.
  --cli-user <name>   Install it for this user instead of the one who ran sudo

SCIM for your IGA (MC only):
  By default your IGA (Saviynt, ISC) reaches the MC's SCIM 2.0 server through
  the Klyro relay, over the MC's own outbound connection. --scim-host also
  exposes it directly, through an Ingress, for an IGA that can reach that
  name. The choice is saved in ConfigMap klyro-mc-agent-info: a re-run
  without --scim-* flags keeps it.
  --scim-host <host>  Expose it at https://<host>, a DNS name that your IGA
                      resolves to the cluster's ingress controller
  --no-scim-ingress   Do not expose it (the relay through Klyro Cloud stays)
  --scim-ingress-class <class>
                      IngressClass for it (default: the cluster's default
                      class, traefik on k3s)
  --scim-tls-secret <name>
                      Existing kubernetes.io/tls Secret in klyro-system with
                      the certificate for <host>
  --scim-tls-cert <path>, --scim-tls-key <path>
                      PEM certificate (chain) and private key for <host>; the
                      installer writes them to Secret klyro-mc-scim-tls

Credential store (MC only):
  By default the MC keeps connection credentials in its own Secret
  klyro-mc-credentials: Klyro Cloud hands it a value and keeps only a
  reference, and the squad (klyro onboard on the MC's VM) writes there through
  ServiceAccount klyro-mc-squad. The choice is saved in ConfigMap
  klyro-mc-agent-info: a re-run without either flag keeps it.
  --no-credential-store
                      Do not: no klyro-mc-credentials writes and no squad
                      ServiceAccount (keys already stored are kept)
  --credential-store  Turn it back on after --no-credential-store

Restricted egress:
  --proxy <url>       http:// proxy for the agent, worker and OTel collector
                      (proxy.* chart values) and the k3s that --bootstrap
                      installs. MC S3 backup Jobs do not use it and need their
                      own egress. Without --proxy, an http:// HTTPS_PROXY (or
                      https_proxy) in your shell is used for them; an https://
                      one is ignored with a warning. The installer's own
                      curl, helm and kubectl follow your shell's HTTPS_PROXY.
  --no-proxy <list>   Extra comma-separated NO_PROXY entries for the pods, e.g.
                      the cluster's pod/service CIDRs on non-k3s clusters and
                      internal target applications. When the proxy comes from
                      HTTPS_PROXY, defaults to your shell's NO_PROXY minus the
                      entries the chart always sets
  --ca-file <path>    PEM bundle of extra CAs the pods trust (a TLS-inspecting
                      proxy's root); ConfigMap klyro-extra-ca, chart value extraCA
  --chart-repo <oci>  Self-upgrade chart repository (agent.helm.chartRepo).
                      Researcher default oci://ghcr.io/klyrohq/klyro-security/charts,
                      MC default oci://registry[.env].klyro.security/klyrohq/klyro-security/charts

Preflight:
  --preflight         Check this host, its network and Klyro Cloud without
                      installing or changing anything, and print a report to
                      send to Klyro. Takes the same flags as the install
                      (--env, --product, --bootstrap, --proxy, --ca-file, ...);
                      the install token is optional and never redeemed. Exits
                      0 when nothing fails, 1 otherwise. Not with --local or
                      --reinstall.
  --bedrock-region <r>
                      AWS region the Bedrock check targets (default us-east-1)

Local Mode (--local):
  Sets up a complete local environment:
  - k3d cluster with local registry
  - Mock Cloud gRPC server for agent registration
  - Temporal for workflow orchestration
  - Agent + Worker/Operator fully connected
  - Anthropic credentials (dummy key for testing)

Local Mode with Custom Endpoints (--local --grpc-endpoint):
  Sets up local k3d cluster but connects to real/external cloud:
  - k3d cluster with local registry
  - Temporal for workflow orchestration
  - Agent connects to specified gRPC endpoint (no mock cloud)
  - Skips mock cloud connectivity tests

Production Mode:
  Requires the following environment variables:
  - ANTHROPIC_API_KEY (mandatory) - Anthropic API key for the AI worker

Get your install token:
  1. Log in to https://app.klyro.security
  2. Navigate to Agents → Add Agent
  3. Copy the install command

Environment Variables:
  ANTHROPIC_API_KEY (mandatory for prod) Anthropic API key for AI-powered provisioning
  KLYRO_API_URL    Override API endpoint (default: https://api.klyro.security)
  KLYRO_ENV        Same as --env flag (flag takes precedence)
  KLYRO_PRODUCT    Same as --product flag (flag takes precedence; default researcher,mc,cli)
  KLYRO_DEBUG      Enable debug output (set to 'true')

Examples:
  # Full local mode with mock cloud
  ./install.sh inst_test --local

  # Local k3d cluster connecting to real cloud
  ./install.sh inst_abc123 --local --grpc-endpoint grpc.klyro.security:443

  # Production installation: Researcher and MC, MC on the bundled database
  ANTHROPIC_API_KEY=sk-ant-... ./install.sh inst_abc123

  # One line on a bare host: k3s, Researcher, MC and the klyro CLI for you
  curl -fsSL https://get.klyro.security/install.sh | sudo bash -s -- --bootstrap inst_abc123

  # Researcher only
  ANTHROPIC_API_KEY=sk-ant-... ./install.sh inst_abc123 --product researcher

  # Researcher and MC from one token, MC on your own PostgreSQL
  ./install.sh inst_abc123 --mc-database-url-file ./mc-db-url

  # MC with its SCIM server exposed to your IGA at https://scim.example.com
  ./install.sh inst_abc123 --product mc --scim-host scim.example.com \
      --scim-tls-cert ./scim.crt --scim-tls-key ./scim.key

  # E2E testing with Temporal (deploys Temporal alongside agent)
  ANTHROPIC_API_KEY=sk-ant-... ./install.sh inst_abc123 --with-temporal

EOF
    exit 0
}

# =============================================================================
# LOCAL MODE FUNCTIONS
# =============================================================================

check_local_prerequisites() {
    log_local "Checking local mode prerequisites..."

    local MISSING=0

    check_command "docker" "brew install --cask docker" || MISSING=1
    check_command "k3d" "brew install k3d" || MISSING=1
    check_command "go" "brew install go" || MISSING=1

    if [ "$MISSING" -eq 1 ]; then
        echo ""
        log_error "Missing local mode tools. Please install them and try again."
        exit 1
    fi

    if ! docker info >/dev/null 2>&1; then
        log_error "Docker daemon is not running. Start Docker Desktop."
        exit 1
    fi

    log_success "Local mode prerequisites verified"
}

create_k3d_cluster() {
    local cluster_name="klyro-local"

    log_local "Setting up k3d cluster..."

    if k3d cluster list 2>/dev/null | grep -q "$cluster_name"; then
        log_info "Cluster '$cluster_name' already exists"
        k3d kubeconfig merge "$cluster_name" --kubeconfig-switch-context >/dev/null 2>&1
        export KUBECONFIG=$(k3d kubeconfig write "$cluster_name")
        return 0
    fi

    log_info "Creating k3d cluster with local registry..."
    k3d cluster create "$cluster_name" \
        --registry-create klyro-registry:0.0.0.0:5000 \
        --port "8090:80@loadbalancer" \
        --port "8443:443@loadbalancer" \
        --port "7233:7233@loadbalancer" \
        --agents 1 \
        --wait

    export KUBECONFIG=$(k3d kubeconfig write "$cluster_name")

    log_info "Waiting for cluster to be ready..."
    kubectl wait --for=condition=Ready nodes --all --timeout=120s

    log_success "k3d cluster '$cluster_name' created"
}

build_local_images() {
    log_local "Building Docker images..."

    local registry="localhost:5000"

    if [ ! -d "${PROJECT_ROOT}/gen/go" ]; then
        log_info "Generating proto files..."
        cd "${PROJECT_ROOT}"
        make proto || {
            log_warn "Proto generation failed - checking if gen/ exists..."
            if [ ! -d "${PROJECT_ROOT}/gen/go" ]; then
                log_error "Proto files not found. Run 'make proto' first."
                exit 1
            fi
        }
    fi

    log_info "Building agent image..."
    docker build -t ${registry}/klyro-agent:local \
        -f "${PROJECT_ROOT}/services/agent/Dockerfile" \
        "${PROJECT_ROOT}" || {
        log_error "Failed to build agent image"
        exit 1
    }
    docker push ${registry}/klyro-agent:local
    log_success "Agent image built and pushed"

    log_info "Building operator/worker image..."
    GH_TOKEN="${GH_TOKEN:-$(gh auth token 2>/dev/null || true)}"
    if [ -z "$GH_TOKEN" ]; then
        log_error "The operator image needs a GitHub token that can read klyrohq/klyro releases: run 'gh auth login' or set GH_TOKEN"
        exit 1
    fi
    docker build -t klyro-base:local \
        -f "${PROJECT_ROOT}/docker/base/Dockerfile" \
        "${PROJECT_ROOT}/docker/base" || {
        log_error "Failed to build base image"
        exit 1
    }
    GH_TOKEN="$GH_TOKEN" docker build -t ${registry}/klyro-operator:local \
        --secret id=gh_token,env=GH_TOKEN \
        --build-arg BASE_IMAGE=klyro-base:local \
        -f "${PROJECT_ROOT}/services/operator/Dockerfile" \
        "${PROJECT_ROOT}/services/operator" || {
        log_error "Failed to build operator image"
        exit 1
    }
    docker push ${registry}/klyro-operator:local
    log_success "Operator image built and pushed"

    if [ -z "$CUSTOM_GRPC_ENDPOINT" ]; then
        log_info "Building mock-cloud image..."
        docker build -t ${registry}/mock-cloud:local \
            -f "${PROJECT_ROOT}/services/agent/cmd/mock-cloud/Dockerfile" \
            "${PROJECT_ROOT}" || {
            log_error "Failed to build mock-cloud image"
            exit 1
        }
        docker push ${registry}/mock-cloud:local
        log_success "Mock-cloud image built and pushed"
    else
        log_info "Skipping mock-cloud build (using custom gRPC endpoint)"
    fi

    log_success "All images built and pushed to local registry"
}

start_mock_cloud() {
    log_local "Starting Mock Cloud gRPC server..."

    if kubectl get deployment mock-cloud -n "$NAMESPACE" >/dev/null 2>&1; then
        log_info "Mock Cloud already deployed"
        return 0
    fi

    kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mock-cloud
  namespace: $NAMESPACE
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mock-cloud
  template:
    metadata:
      labels:
        app: mock-cloud
    spec:
      containers:
      - name: mock-cloud
        image: klyro-registry:5000/mock-cloud:local
        imagePullPolicy: Always
        ports:
        - containerPort: 50051
          name: grpc
        - containerPort: 50052
          name: http
        resources:
          requests:
            cpu: 50m
            memory: 64Mi
          limits:
            cpu: 200m
            memory: 128Mi
---
apiVersion: v1
kind: Service
metadata:
  name: mock-cloud
  namespace: $NAMESPACE
spec:
  selector:
    app: mock-cloud
  ports:
  - name: grpc
    port: 50051
    targetPort: 50051
  - name: http
    port: 50052
    targetPort: 50052
EOF

    log_info "Waiting for Mock Cloud to be ready..."
    kubectl wait --for=condition=Available deployment/mock-cloud -n "$NAMESPACE" --timeout=120s || {
        log_warn "Mock Cloud not ready yet, continuing..."
    }

    log_success "Mock Cloud deployed"
}

start_temporal() {
    log_local "Starting Temporal..."

    if kubectl get pods -n "$NAMESPACE" -l app=temporal 2>/dev/null | grep -q "Running"; then
        log_info "Temporal already running"
        return 0
    fi

    log_info "Deploying Temporal with PostgreSQL..."

    # Generate random password for Temporal PostgreSQL (or reuse existing secret)
    local TEMPORAL_PG_PASSWORD
    TEMPORAL_PG_PASSWORD=$(kubectl get secret temporal-postgresql-credentials -n "$NAMESPACE" \
        -o jsonpath='{.data.password}' 2>/dev/null | base64 -d 2>/dev/null)
    if [ -z "$TEMPORAL_PG_PASSWORD" ]; then
        TEMPORAL_PG_PASSWORD=$(openssl rand -hex 16 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
        kubectl create secret generic temporal-postgresql-credentials \
            --from-literal=username=temporal \
            --from-literal=password="$TEMPORAL_PG_PASSWORD" \
            --from-literal=database=temporal \
            --namespace="$NAMESPACE" \
            --dry-run=client -o yaml | kubectl apply -f - >/dev/null
        printf "    ${GREEN}[OK]${NC} Secret: temporal-postgresql-credentials (generated)\n"
    else
        printf "    ${GREEN}[OK]${NC} Secret: temporal-postgresql-credentials (existing)\n"
    fi

    kubectl apply -f - <<EOF
---
apiVersion: v1
kind: Service
metadata:
  name: temporal-postgresql
  namespace: $NAMESPACE
spec:
  selector:
    app: temporal-postgresql
  ports:
  - port: 5432
    targetPort: 5432
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: temporal-postgresql-data
  namespace: $NAMESPACE
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: temporal-postgresql
  namespace: $NAMESPACE
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: temporal-postgresql
  template:
    metadata:
      labels:
        app: temporal-postgresql
    spec:
      containers:
      - name: postgresql
        image: ${REGISTRY_PREFIX}library/postgres:15-alpine
        ports:
        - containerPort: 5432
        env:
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: temporal-postgresql-credentials
              key: username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: temporal-postgresql-credentials
              key: password
        - name: POSTGRES_DB
          valueFrom:
            secretKeyRef:
              name: temporal-postgresql-credentials
              key: database
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
        resources:
          requests:
            cpu: 100m
            memory: 256Mi
          limits:
            cpu: 500m
            memory: 512Mi
        readinessProbe:
          exec:
            command: ["pg_isready", "-U", "temporal"]
          initialDelaySeconds: 5
          periodSeconds: 10
        livenessProbe:
          exec:
            command: ["pg_isready", "-U", "temporal"]
          initialDelaySeconds: 15
          periodSeconds: 20
      volumes:
      - name: data
        persistentVolumeClaim:
          claimName: temporal-postgresql-data
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: temporal
  namespace: $NAMESPACE
spec:
  replicas: 1
  selector:
    matchLabels:
      app: temporal
  template:
    metadata:
      labels:
        app: temporal
    spec:
      containers:
      - name: temporal
        image: ${REGISTRY_PREFIX}temporalio/auto-setup:1.24.2
        ports:
        - containerPort: 7233
          name: grpc
        env:
        - name: DB
          value: postgres12
        - name: DB_PORT
          value: "5432"
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: temporal-postgresql-credentials
              key: username
        - name: POSTGRES_PWD
          valueFrom:
            secretKeyRef:
              name: temporal-postgresql-credentials
              key: password
        - name: POSTGRES_SEEDS
          value: temporal-postgresql
        resources:
          requests:
            cpu: 100m
            memory: 256Mi
          limits:
            cpu: 500m
            memory: 512Mi
---
apiVersion: v1
kind: Service
metadata:
  name: temporal-frontend
  namespace: $NAMESPACE
spec:
  selector:
    app: temporal
  ports:
  - name: grpc
    port: 7233
    targetPort: 7233
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: temporal-ui
  namespace: $NAMESPACE
spec:
  replicas: 1
  selector:
    matchLabels:
      app: temporal-ui
  template:
    metadata:
      labels:
        app: temporal-ui
    spec:
      containers:
      - name: temporal-ui
        image: ${REGISTRY_PREFIX}temporalio/ui:2.26.2
        ports:
        - containerPort: 8080
        env:
        - name: TEMPORAL_ADDRESS
          value: temporal-frontend:7233
        resources:
          requests:
            cpu: 50m
            memory: 64Mi
          limits:
            cpu: 200m
            memory: 256Mi
---
apiVersion: v1
kind: Service
metadata:
  name: temporal-web
  namespace: $NAMESPACE
spec:
  selector:
    app: temporal-ui
  ports:
  - port: 8088
    targetPort: 8080
EOF

    log_info "Waiting for PostgreSQL..."
    kubectl wait --for=condition=Available deployment/temporal-postgresql \
        -n "$NAMESPACE" --timeout=120s || {
        log_warn "PostgreSQL deployment not ready yet"
    }

    log_info "Waiting for Temporal (this may take a minute)..."
    sleep 10  # Give PostgreSQL time to initialize

    kubectl wait --for=condition=Available deployment/temporal \
        -n "$NAMESPACE" --timeout=300s || {
        log_warn "Temporal not ready yet, continuing..."
        kubectl get pods -n "$NAMESPACE" -l app=temporal
    }

    log_success "Temporal deployed"
}

fetch_credentials_local() {
    if [ -n "$CUSTOM_API_ENDPOINT" ]; then
        log_local "Fetching credentials from platform API..."

        # POSIX equivalent of ${CUSTOM_API_ENDPOINT//host.docker.internal/localhost}
        local host_api_endpoint
        host_api_endpoint=$(printf '%s' "$CUSTOM_API_ENDPOINT" | sed 's/host\.docker\.internal/localhost/g')
        local api_url="${host_api_endpoint}/api/v1/agents/install?token=${INSTALL_TOKEN}"
        log_info "Calling: $api_url"

        local RESPONSE_FILE=$(mktemp)
        local HTTP_CODE

        HTTP_CODE=$(curl -s -w "%{http_code}" -o "$RESPONSE_FILE" "$api_url" 2>/dev/null) || HTTP_CODE="000"

        case "$HTTP_CODE" in
            200)
                log_success "Credentials retrieved from platform"
                ;;
            401|403)
                log_error "Invalid or expired install token"
                rm -f "$RESPONSE_FILE"
                exit 1
                ;;
            404)
                log_error "Install endpoint not found at: $api_url"
                rm -f "$RESPONSE_FILE"
                exit 1
                ;;
            409)
                log_error "Install token has already been used"
                rm -f "$RESPONSE_FILE"
                exit 1
                ;;
            000)
                log_error "Cannot connect to platform API at: $CUSTOM_API_ENDPOINT"
                rm -f "$RESPONSE_FILE"
                exit 1
                ;;
            *)
                log_error "API error (HTTP $HTTP_CODE)"
                cat "$RESPONSE_FILE" 2>/dev/null || true
                rm -f "$RESPONSE_FILE"
                exit 1
                ;;
        esac

        local RESPONSE=$(cat "$RESPONSE_FILE")
        rm -f "$RESPONSE_FILE"

        AGENT_ID=$(json_value "$RESPONSE" "agent_id")
        TENANT_ID=$(json_value "$RESPONSE" "tenant_id")
        SITE_ID=$(json_value "$RESPONSE" "site_id")
        CHART_VERSION=$(json_value "$RESPONSE" "chart_version")
        OAUTH2_CLIENT_ID=$(json_value "$RESPONSE" "oauth2_client_id")
        OAUTH2_CLIENT_SECRET=$(json_value "$RESPONSE" "oauth2_client_secret")
        GHCR_TOKEN=$(json_value "$RESPONSE" "ghcr_token")
        ACCESS_TOKEN="$OAUTH2_CLIENT_SECRET"

        # Validate required fields
        if [ -z "$AGENT_ID" ] || [ -z "$OAUTH2_CLIENT_ID" ] || [ -z "$OAUTH2_CLIENT_SECRET" ]; then
            log_error "Incomplete response from API - missing required credentials"
            log_info "Response: $RESPONSE"
            exit 1
        fi

        echo ""
        echo "    ┌─────────────────────────────────────────────────────┐"
        echo "    │  Agent ID:      $AGENT_ID"
        echo "    │  Tenant ID:     $TENANT_ID"
        echo "    │  Site ID:       $SITE_ID"
        echo "    │  OAuth Client:  $OAUTH2_CLIENT_ID"
        echo "    │  Mode:          LOCAL + Custom Endpoints"
        echo "    └─────────────────────────────────────────────────────┘"
        return 0
    fi

    log_local "Using local mock credentials..."

    case "$INSTALL_TOKEN" in
        inst_*)
            ;;
        *)
            INSTALL_TOKEN="inst_${INSTALL_TOKEN}"
            log_info "Prefixed token with 'inst_' for mock cloud compatibility"
            ;;
    esac

    # $RANDOM is a bashism; fall back to the PID under a POSIX shell so the
    # generated local-test values still differ between hosts/runs.
    AGENT_ID="klyro_local_test"
    ACCESS_TOKEN="kat_local_test_token_${RANDOM:-$$}"
    CHART_VERSION="local"
    ECR_TOKEN=""

    OAUTH2_CLIENT_ID="klyro-edge-local-test"
    OAUTH2_CLIENT_SECRET="local_test_secret_${RANDOM:-$$}"

    echo ""
    echo "    ┌─────────────────────────────────────────────────────┐"
    echo "    │  Install Token: $INSTALL_TOKEN"
    echo "    │  Agent ID:      $AGENT_ID"
    echo "    │  Mode:          LOCAL (mock cloud)"
    echo "    │  gRPC:          mock-cloud:50051"
    echo "    │  Temporal:      temporal-frontend:7233"
    echo "    └─────────────────────────────────────────────────────┘"
}

create_local_secrets() {
    log_local "Creating local test secrets..."

    # Create dummy OpenAI credentials (required by worker)
    kubectl create secret generic openai-credentials \
        --from-literal=api-key="sk-local-test-key-not-real" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null

    printf "    ${GREEN}[OK]${NC} Secret: openai-credentials (dummy for local testing)\n"
}

install_helm_chart_local() {
    log_local "Installing Helm chart in local mode..."

    local CHART_PATH="${PROJECT_ROOT}/charts/klyro-edge"

    if [ ! -d "$CHART_PATH" ]; then
        log_error "Chart not found at: $CHART_PATH"
        exit 1
    fi

    # Determine gRPC endpoint and TLS settings
    local grpc_endpoint="mock-cloud:50051"
    local grpc_insecure="true"

    if [ -n "$CUSTOM_GRPC_ENDPOINT" ]; then
        grpc_endpoint="$CUSTOM_GRPC_ENDPOINT"
        # If endpoint contains standard TLS ports or https, use secure connection
        case "$grpc_endpoint" in
            *:443*|grpc.*)
                grpc_insecure="false"
                ;;
        esac
        log_info "Using custom gRPC endpoint: $grpc_endpoint (insecure=$grpc_insecure)"
    fi

    # Determine API endpoint
    local api_endpoint="https://api.klyro.security"
    if [ -n "$CUSTOM_API_ENDPOINT" ]; then
        api_endpoint="$CUSTOM_API_ENDPOINT"
        log_info "Using custom API endpoint: $api_endpoint"
    fi

    HELM_ARGS="--namespace $NAMESPACE"
    if [ -n "$GHCR_TOKEN" ]; then
        log_info "Using GHCR registry: ${GHCR_REGISTRY}"
        HELM_ARGS="$HELM_ARGS --set global.imagePullSecrets[0].name=klyro-registry-secret"
        # Agent configuration using GHCR
        HELM_ARGS="$HELM_ARGS --set agent.image.repository=${GHCR_REGISTRY}/klyro-agent"
        HELM_ARGS="$HELM_ARGS --set agent.image.tag=${CHART_VERSION:-latest}"
        # Worker configuration using GHCR
        HELM_ARGS="$HELM_ARGS --set worker.image.repository=${GHCR_REGISTRY}/klyro-operator"
        HELM_ARGS="$HELM_ARGS --set worker.image.tag=${CHART_VERSION:-latest}"
    else
        log_info "Using local k3d registry (no GHCR token)"
        HELM_ARGS="$HELM_ARGS --set global.imagePullSecrets=null"
        # Agent configuration - use full image path to local registry
        HELM_ARGS="$HELM_ARGS --set agent.image.repository=klyro-registry:5000/klyro-agent"
        HELM_ARGS="$HELM_ARGS --set agent.image.tag=local"
        # Worker configuration - use full image path to local registry
        HELM_ARGS="$HELM_ARGS --set worker.image.repository=klyro-registry:5000/klyro-operator"
        HELM_ARGS="$HELM_ARGS --set worker.image.tag=local"
    fi

    HELM_ARGS="$HELM_ARGS --set agent.image.pullPolicy=Always"
    HELM_ARGS="$HELM_ARGS --set agent.persistence.enabled=true"
    HELM_ARGS="$HELM_ARGS --set agent.persistence.storageClass=local-path"

    HELM_ARGS="$HELM_ARGS --set klyroCloud.endpoint=$api_endpoint"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.grpc.endpoint=$grpc_endpoint"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.grpc.insecure=$grpc_insecure"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.gatewayHttpUrl=$api_endpoint"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.apiKeySecretName=klyro-cloud-credentials"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.apiKeySecretKey=access-token"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.agentIdSecretKey=agent-id"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.heartbeat.enabled=true"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.heartbeat.intervalSeconds=10"

    HELM_ARGS="$HELM_ARGS --set worker.enabled=true"
    HELM_ARGS="$HELM_ARGS --set worker.image.pullPolicy=Always"
    HELM_ARGS="$HELM_ARGS --set worker.temporal.hostPort=temporal-frontend:7233"
    HELM_ARGS="$HELM_ARGS --set worker.temporal.namespace=default"
    HELM_ARGS="$HELM_ARGS --set worker.temporal.taskQueue=klyro-tasks"

    HELM_ARGS="$HELM_ARGS --set temporal.enabled=false"
    HELM_ARGS="$HELM_ARGS --set temporal.mysql.enabled=false"
    HELM_ARGS="$HELM_ARGS --set temporal-mysql.enabled=false"

    HELM_ARGS="$HELM_ARGS --set opentelemetry.enabled=false"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.clusterName=$AGENT_ID"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.enabled=false"

    HELM_ARGS="$HELM_ARGS --set ecr.enabled=false"
    HELM_ARGS="$HELM_ARGS --set imagePullSecrets.create=false"

    HELM_ARGS="$HELM_ARGS --wait --timeout 15m"

    log_info "Running Helm install..."
    helm upgrade --install "$RELEASE_NAME" "$CHART_PATH" $HELM_ARGS || {
        log_error "Helm installation failed"
        echo ""
        echo "Debug commands:"
        echo "  kubectl get pods -n $NAMESPACE"
        echo "  kubectl describe pods -n $NAMESPACE"
        exit 1
    }

    log_success "Helm chart installed"
}

verify_local_installation() {
    log_local "Verifying local installation..."

    echo ""

    printf "    Checking Mock Cloud... "
    if kubectl get pods -n "$NAMESPACE" -l app=mock-cloud 2>/dev/null | grep -q "Running"; then
        printf "${GREEN}OK${NC}\n"
    else
        printf "${YELLOW}PENDING${NC}\n"
    fi

    printf "    Checking Temporal... "
    if kubectl get pods -n "$NAMESPACE" -l app.kubernetes.io/component=frontend 2>/dev/null | grep -q "Running"; then
        printf "${GREEN}OK${NC}\n"
    else
        printf "${YELLOW}PENDING${NC}\n"
    fi

    printf "    Checking Agent... "
    if kubectl get pods -n "$NAMESPACE" -l app.kubernetes.io/component=agent 2>/dev/null | grep -q "Running"; then
        printf "${GREEN}OK${NC}\n"
    else
        printf "${YELLOW}PENDING${NC}\n"
    fi

    printf "    Checking Worker... "
    if kubectl get pods -n "$NAMESPACE" -l app.kubernetes.io/component=worker 2>/dev/null | grep -q "Running"; then
        printf "${GREEN}OK${NC}\n"
    else
        printf "${YELLOW}PENDING${NC}\n"
    fi

    echo ""

    log_info "Waiting for agent to be ready..."
    kubectl rollout status deployment/${RELEASE_NAME}-agent \
        -n "$NAMESPACE" --timeout=120s 2>/dev/null || {
        log_warn "Agent deployment taking longer than expected"
    }

    sleep 3
    local POD_NAME=$(kubectl get pods -n "$NAMESPACE" \
        -l app.kubernetes.io/component=agent \
        -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)

    if [ -n "$POD_NAME" ]; then
        log_info "Testing agent health..."
        # curl, not wget: the agent image ships curl and has no wget (KAN-696).
        local HEALTH=$(kubectl exec -n "$NAMESPACE" "$POD_NAME" -- \
            curl -sf http://localhost:8080/health 2>/dev/null || echo "")

        if printf '%s\n' "$HEALTH" | grep -qi "ok"; then
            printf "    ${GREEN}[OK]${NC} Agent health check passed\n"
        else
            printf "    ${YELLOW}[WARN]${NC} Agent health check inconclusive\n"
        fi

        log_info "Checking agent connectivity..."
        local LOGS=$(kubectl logs -n "$NAMESPACE" "$POD_NAME" --tail=50 2>/dev/null)

        # printf, not echo: $LOGS is arbitrary kubectl log text and dash's echo would
        # expand any \t / \n / \\ in it, which can flip the grep result.
        if printf '%s\n' "$LOGS" | grep -qi "connected.*grpc\|heartbeat.*started\|control stream"; then
            printf "    ${GREEN}[OK]${NC} Agent connected to gRPC cloud\n"
        else
            printf "    ${YELLOW}[INFO]${NC} Agent gRPC connection pending\n"
        fi

        if printf '%s\n' "$LOGS" | grep -qi "temporal\|connector.*initialized"; then
            printf "    ${GREEN}[OK]${NC} Agent connected to Temporal\n"
        else
            printf "    ${YELLOW}[INFO]${NC} Agent Temporal connection pending\n"
        fi
    fi

    echo ""
    log_info "Pod status:"
    kubectl get pods -n "$NAMESPACE" -o wide 2>/dev/null | sed 's/^/    /'
}

run_connectivity_tests() {
    log_local "Running connectivity tests..."

    echo ""

    local AGENT_POD=$(kubectl get pods -n "$NAMESPACE" \
        -l app.kubernetes.io/component=agent \
        -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)

    if [ -z "$AGENT_POD" ]; then
        log_warn "Agent pod not found, skipping tests"
        return 1
    fi

    # Test 1: Agent Health
    printf "    Test 1: Agent Health... "
    if kubectl exec -n "$NAMESPACE" "$AGENT_POD" -- curl -sf http://localhost:8080/health 2>/dev/null | grep -qi "ok"; then
        printf "${GREEN}PASS${NC}\n"
    else
        printf "${RED}FAIL${NC}\n"
    fi

    # Test 2: Agent Status API
    printf "    Test 2: Agent Status API... "
    if kubectl exec -n "$NAMESPACE" "$AGENT_POD" -- curl -sf http://localhost:8080/api/v1/status 2>/dev/null | grep -qi "agent"; then
        printf "${GREEN}PASS${NC}\n"
    else
        printf "${RED}FAIL${NC}\n"
    fi

    # Test 3: SQLite Database
    printf "    Test 3: SQLite Database... "
    if kubectl exec -n "$NAMESPACE" "$AGENT_POD" -- ls /data/klyro.db 2>/dev/null; then
        printf "${GREEN}PASS${NC}\n"
    else
        printf "${YELLOW}PENDING${NC} (DB will be created on first write)\n"
    fi

    # Test 4: Temporal Frontend Reachability
    printf "    Test 4: Temporal Frontend... "
    if kubectl exec -n "$NAMESPACE" "$AGENT_POD" -- \
        curl -sf --max-time 5 http://temporal-frontend:7233 2>&1 | grep -qi "error\|refused"; then
        printf "${YELLOW}PENDING${NC}\n"
    else
        printf "${GREEN}REACHABLE${NC}\n"
    fi

    # Test 5: Mock Cloud gRPC Reachability
    printf "    Test 5: Mock Cloud gRPC... "
    if kubectl exec -n "$NAMESPACE" "$AGENT_POD" -- \
        curl -sf --max-time 5 http://mock-cloud:50052/agents 2>/dev/null; then
        printf "${GREEN}REACHABLE${NC}\n"
    else
        printf "${YELLOW}PENDING${NC}\n"
    fi

    echo ""
    log_success "Connectivity tests completed"
}

# =============================================================================
# Prerequisites Check
# =============================================================================

check_command() {
    if ! command -v "$1" >/dev/null 2>&1; then
        log_error "$1 not found"
        echo "  Install: $2"
        return 1
    fi
    return 0
}

# Sets EV_STATUS ok (root or passwordless sudo), fail (neither, with --bootstrap) or
# warn (neither), with EV_DETAIL and EV_FIX.
# With $1 = preflight, sudo -n -l first: unlike sudo -n true, it never logs or mails
# "user NOT in sudoers" for a user sudoers does not list, and it runs no command. Not
# sudo -n -v: under the default verifypw=all it fails when any of the user's entries
# needs a password (say %wheel ALL=(ALL) ALL beside a NOPASSWD: ALL one), while -l under
# the default listpw=any passes when any entry is NOPASSWD, as sudo -n true does.
eval_root_or_sudo() {
    EV_FIX="Re-run as root, or as a user for whom 'sudo -n true' succeeds."
    if [ "$(id -u)" -eq 0 ]; then
        EV_STATUS=ok EV_DETAIL="running as root"
    elif command -v sudo >/dev/null 2>&1 && { [ "${1:-}" != preflight ] || sudo -n -l >/dev/null 2>&1; } \
        && sudo -n true 2>/dev/null; then
        EV_STATUS=ok EV_DETAIL="passwordless sudo"
    elif [ "${bootstrap_cluster:-}" = "true" ]; then
        EV_STATUS=fail EV_DETAIL="--bootstrap needs root or passwordless sudo"
    else
        EV_STATUS=warn EV_DETAIL="not root and no passwordless sudo"
    fi
}

# Runs its arguments as root: through sudo -n when AS_ROOT_SUDO is true.
as_root() {
    if [ "${AS_ROOT_SUDO:-}" = "true" ]; then
        sudo -n "$@"
    else
        "$@"
    fi
}

require_root_or_sudo() {
    eval_root_or_sudo
    if [ "$EV_STATUS" != "ok" ]; then
        log_error "--bootstrap needs root or passwordless sudo"
        echo "  $EV_FIX"
        exit 1
    fi
}

use_k3s_kubeconfig() {
    local src=/etc/rancher/k3s/k3s.yaml dest
    if [ "$(id -u)" -eq 0 ] || [ -r "$src" ]; then
        export KUBECONFIG="$src"
        return
    fi
    require_root_or_sudo
    [ -d "$HOME/.kube" ] || mkdir -m 700 "$HOME/.kube"
    if [ ! -x "$HOME/.kube" ] || [ ! -w "$HOME/.kube" ]; then
        log_error "$HOME/.kube exists but is not writable/traversable by $(id -un)"
        echo "  Fix its ownership and re-run: sudo chown \"\$(id -u):\$(id -g)\" ~/.kube"
        exit 1
    fi
    dest="$HOME/.kube/config"
    if [ -e "$dest" ] && ! sudo cat "$src" | cmp -s - "$dest"; then
        dest="$HOME/.kube/klyro-k3s.yaml"
        if [ -e "$dest" ] && ! sudo cat "$src" | cmp -s - "$dest"; then
            if ! dest=$(mktemp "$HOME/.kube/klyro-k3s.XXXXXX"); then
                log_error "Failed to create a kubeconfig file in $HOME/.kube"
                exit 1
            fi
        fi
    fi
    if ! sudo install -m 600 -o "$(id -u)" -g "$(id -g)" "$src" "$dest"; then
        log_error "Failed to copy $src to $dest"
        exit 1
    fi
    export KUBECONFIG="$dest"
    log_info "k3s kubeconfig copied to $dest"
}

K3S_REGISTRIES_DEFAULT="/etc/rancher/k3s/registries.yaml"
K3S_YUM_REPO_DIR="/etc/yum.repos.d"
K3S_SELINUX_REPO="klyro-k3s-selinux"

# Runs its arguments as root: directly as root, else through sudo -n (bootstrap has
# already required root or passwordless sudo).
k3s_root() {
    if [ "$(id -u)" -eq 0 ]; then
        "$@"
    else
        sudo -n "$@"
    fi
}

# The NO_PROXY of k3s and containerd under --proxy, comma-separated: this shell's
# NO_PROXY and no_proxy, NO_PROXY_EXTRA, localhost and 127.0.0.1, each entry once.
node_no_proxy() {
    printf '%s\n' "${NO_PROXY:-},${no_proxy:-},${NO_PROXY_EXTRA:-},localhost,127.0.0.1" | tr ',' '\n' \
        | sed 's/[[:space:]]//g' | awk '$0 == "" || seen[$0]++ { next } { out = out (out == "" ? "" : ",") $0 } END { print out }'
}

# Runs command $@ (a program, not a shell function) with --proxy, when given, as its
# proxy, the route k3s and containerd take: the k3s installer, and the dnf that
# installs the SELinux packages. With $1 = root, as root; sudo -n env keeps the proxy
# variables sudo would drop.
k3s_proxy_run() {
    local as_root_too=false k3s_no_proxy
    if [ "$1" = root ]; then
        as_root_too=true
        shift
    fi
    if [ -n "$PROXY_URL" ]; then
        k3s_no_proxy=$(node_no_proxy)
        set -- env "HTTP_PROXY=$PROXY_URL" "HTTPS_PROXY=$PROXY_URL" "NO_PROXY=$k3s_no_proxy" \
            "http_proxy=$PROXY_URL" "https_proxy=$PROXY_URL" "no_proxy=$k3s_no_proxy" "$@"
    fi
    if [ "$as_root_too" = true ] && [ "$(id -u)" -ne 0 ]; then
        sudo -n "$@"
    else
        "$@"
    fi
}

# A k3s version as it appears in a URL: + percent-encoded, as the k3s installer does.
k3s_url_version() {
    printf '%s\n' "$1" | sed 's/+/%2B/g'
}

# The k3s installer script, from the Klyro CDN mirror of the pinned version.
k3s_installer_url() {
    printf 'https://%s/k3s/%s/install.sh\n' "$KLYRO_CDN" "$(k3s_url_version "$K3S_VERSION")"
}

# Where the k3s installer gets the binary and its checksums: INSTALL_K3S_ARTIFACT_URL
# and INSTALL_K3S_VERSION from the environment (a site's own mirror), else the Klyro
# CDN and the pinned version. A pinned version means no update.k3s.io lookup.
k3s_artifact_url() {
    printf '%s\n' "${INSTALL_K3S_ARTIFACT_URL:-https://$KLYRO_CDN/k3s}"
}
k3s_version() {
    printf '%s\n' "${INSTALL_K3S_VERSION:-$K3S_VERSION}"
}

# The registries.yaml a new k3s install reads: --private-registry in INSTALL_K3S_EXEC,
# else private-registry in the config file (--config in INSTALL_K3S_EXEC, else
# K3S_CONFIG_FILE) and its drop-ins, else the default path.
new_k3s_registries_file() {
    local f
    f=$(printf '%s\n' "${INSTALL_K3S_EXEC:-}" | k3s_arg private-registry)
    [ -n "$f" ] || f=$(config_value private-registry "$(printf '%s\n' "${INSTALL_K3S_EXEC:-}" | k3s_arg config)")
    printf '%s\n' "${f:-$K3S_REGISTRIES_DEFAULT}"
}

# Points the new k3s's containerd at the Klyro registry for docker.io, so k3s's own
# images (CoreDNS, pause, Traefik, local-path, metrics-server, klipper-helm) come
# through the registry[.env].klyro.security pull-through cache, not Docker Hub. A
# registries.yaml already there is the site's own and is left as it is.
write_k3s_registries() {
    local f
    f=$(new_k3s_registries_file)
    if k3s_root test -e "$f"; then
        log_warn "$f already exists and is left as it is: k3s's system images come from the docker.io mirror it names, else from docker.io"
        echo "  To pull them through Klyro, add to it: mirrors: docker.io: endpoint: [\"https://$KLYRO_REGISTRY\"]"
        return 0
    fi
    k3s_root mkdir -p "$(dirname "$f")"
    printf 'mirrors:\n  docker.io:\n    endpoint:\n      - "https://%s"\n' "$KLYRO_REGISTRY" | k3s_root tee "$f" >/dev/null
    log_info "k3s system images: docker.io mirrored to https://$KLYRO_REGISTRY ($f)"
}

# The rpm.rancher.io directory that holds the k3s-selinux RPM for this host, chosen
# from /etc/os-release as the k3s installer chooses it (centos/7, centos/8 or
# centos/9), or nothing for a host outside the RHEL family (SUSE and rpm-ostree hosts
# included: the k3s installer handles them itself).
k3s_selinux_rpm_infix() {
    local id like ver major
    id=$(pf_os_field ID) like=$(pf_os_field ID_LIKE) ver=$(pf_os_field VERSION_ID)
    [ -z "$(pf_os_field OSTREE_VERSION)" ] || return 0
    case " $id $like " in
        *" suse "*|*" coreos "*) return 0 ;;
        *" rhel "*|*" centos "*|*" fedora "*|*" rocky "*|*" almalinux "*|*" amzn "*) ;;
        *) return 0 ;;
    esac
    major=${ver%%.*}
    if [ -z "$major" ] || [ "$major" = 7 ] || { [ "$id" = amzn ] && [ "$major" = 2 ]; }; then
        echo centos/7
    elif [ "$major" = 8 ]; then
        echo centos/8
    else
        case "$major" in
            *[!0-9]*) echo centos/9 ;;
            *) if [ "$major" -gt 36 ]; then echo centos/8; else echo centos/9; fi ;;
        esac
    fi
}

# Succeeds when the k3s installer would install the k3s-selinux RPM: a RHEL-family
# host with SELinux policy files, the RPM not skipped. The installer then installs it
# itself, from the Klyro CDN, since the k3s installer only knows rpm.rancher.io.
k3s_selinux_rpm_wanted() {
    [ -n "$(k3s_selinux_rpm_infix)" ] || return 1
    [ -d "$PF_SELINUX_DIR" ] || return 1
    [ "${INSTALL_K3S_SKIP_SELINUX_RPM:-}" != true ] || return 1
    case "${INSTALL_K3S_SKIP_DOWNLOAD:-}" in true|selinux) return 1 ;; esac
}

# Installs k3s-selinux for the new k3s, as the k3s installer would, but from the Klyro
# CDN (https://<KLYRO_CDN>/rancher-rpm/, a proxy of rpm.rancher.io), and tells the k3s
# installer to skip its own RPM step. container-selinux comes from the OS repositories.
# Sets K3S_SELINUX_RELABEL=true: the k3s installer labels its binary only in the step
# it now skips, so bootstrap_k3s_cluster labels it.
install_k3s_selinux() {
    local infix pm repo
    K3S_SELINUX_RELABEL=false
    k3s_selinux_rpm_wanted || return 0
    command -v rpm >/dev/null 2>&1 || return 0
    infix=$(k3s_selinux_rpm_infix)
    pm=yum
    [ -x /usr/bin/dnf ] && pm=dnf
    if ! rpm -q container-selinux >/dev/null 2>&1; then
        log_info "Installing container-selinux from the OS repositories (k3s-selinux needs it)..."
        if ! k3s_proxy_run root "$pm" install -y container-selinux; then
            log_error "container-selinux is not installed, and $pm could not install it from the OS repositories"
            echo "  k3s-selinux needs it. Install container-selinux (it ships with RHEL, Rocky, Alma and Amazon Linux)"
            echo "  from your OS repositories or Satellite, then re-run."
            exit 1
        fi
    fi
    if ! rpm -q k3s-selinux >/dev/null 2>&1; then
        repo="$K3S_YUM_REPO_DIR/$K3S_SELINUX_REPO.repo"
        log_info "Installing k3s-selinux from https://$KLYRO_CDN/rancher-rpm/ ..."
        printf '[%s]\nname=k3s-selinux (Klyro mirror of rpm.rancher.io)\nbaseurl=https://%s/rancher-rpm/k3s/stable/common/%s/noarch\nenabled=1\ngpgcheck=1\nrepo_gpgcheck=0\ngpgkey=https://%s/rancher-rpm/public.key\n' \
            "$K3S_SELINUX_REPO" "$KLYRO_CDN" "$infix" "$KLYRO_CDN" | k3s_root tee "$repo" >/dev/null
        if ! k3s_proxy_run root "$pm" install -y --disablerepo='*' --enablerepo="$K3S_SELINUX_REPO" k3s-selinux; then
            log_error "Failed to install k3s-selinux from https://$KLYRO_CDN/rancher-rpm/k3s/stable/common/$infix/noarch"
            echo "  Ensure this host reaches https://$KLYRO_CDN${PROXY_URL:+ through the --proxy}, and that container-selinux is recent enough for it."
            exit 1
        fi
    fi
    INSTALL_K3S_SKIP_SELINUX_RPM=true
    export INSTALL_K3S_SKIP_SELINUX_RPM
    K3S_SELINUX_RELABEL=true
}

# Gives the k3s binary the SELinux type the k3s installer would have given it, had it
# installed k3s-selinux itself. Fails only when SELinux is set to enforcing, as the
# k3s installer does.
label_k3s_binary() {
    local bin="${INSTALL_K3S_BIN_DIR:-/usr/local/bin}/k3s"
    if ! k3s_root chcon -u system_u -r object_r -t container_runtime_exec_t "$bin" >/dev/null 2>&1; then
        if grep -q '^[[:space:]]*SELINUX=enforcing' /etc/selinux/config 2>/dev/null; then
            log_error "Failed to label $bin container_runtime_exec_t (SELinux is enforcing)"
            echo "  Check that k3s-selinux is installed (rpm -q k3s-selinux), then: chcon -t container_runtime_exec_t $bin"
            exit 1
        fi
        log_warn "Could not label $bin container_runtime_exec_t"
    fi
}

# Logs host change $1 that --bootstrap made, and keeps it for the summary.
host_prep_change() {
    log_success "Host prep: $1"
    HOST_PREP_CHANGES="${HOST_PREP_CHANGES:-}${HOST_PREP_CHANGES:+
}$1"
}

# The fapolicyd rules that let k3s run what it unpacks, one per line: k3s's directories,
# and the new install's data dir (new_k3s_data_dir) when it is outside /var/lib/rancher/.
k3s_fapolicyd_rules() {
    local d
    for d in /var/lib/rancher/ /run/k3s/ /var/lib/kubelet/ /opt/cni/; do
        printf 'allow perm=any all : dir=%s\n' "$d"
    done
    d="$(new_k3s_data_dir)"
    d="${d%/}/"
    case "$d" in
        /var/lib/rancher/*) ;;
        *) printf 'allow perm=any all : dir=%s\n' "$d" ;;
    esac
}

# Allows the new k3s in an active fapolicyd before k3s starts: adds the missing
# k3s_fapolicyd_rules lines to rules.d/80-k3s.rules, trusts the k3s binary (exit 9: already
# in the trust database, so its entry is updated to the new binary), then reloads.
prep_fapolicyd() {
    local f="$FAPOLICYD_RULES_DIR/80-k3s.rules" bin="${INSTALL_K3S_BIN_DIR:-/usr/local/bin}/k3s" missing created="" out rc
    if ! k3s_root test -d "$FAPOLICYD_RULES_DIR"; then
        log_warn "fapolicyd is active but $FAPOLICYD_RULES_DIR does not exist: k3s is not allowed in fapolicyd. To allow it, as root:"
        fapolicyd_fix
        return 0
    fi
    k3s_root test -e "$f" || created=yes
    missing=$(k3s_fapolicyd_rules | while IFS= read -r rule; do
        k3s_root grep -qxF -- "$rule" "$f" 2>/dev/null || printf '%s\n' "$rule"
    done)
    if [ -n "$missing" ]; then
        printf '%s\n' "$missing" | k3s_root tee -a "$f" >/dev/null
        [ -z "$created" ] || k3s_root chmod 0644 "$f"
        host_prep_change "fapolicyd: $f allows $(printf '%s\n' "$missing" | sed 's/.*dir=//' | tr '\n' ' ' | sed 's/ $//')"
    fi
    rc=0
    out=$(k3s_root fapolicyd-cli --file add "$bin" --trust-file k3s 2>&1) || rc=$?
    case "$rc" in
        0) host_prep_change "fapolicyd: $bin trusted (trust file k3s)" ;;
        9)
            rc=0
            out=$(k3s_root fapolicyd-cli --file update "$bin" --trust-file k3s 2>&1) || rc=$?
            [ "$rc" -eq 0 ] && host_prep_change "fapolicyd: trust of $bin updated to the new binary (trust file k3s)"
            ;;
    esac
    if [ "$rc" -ne 0 ]; then
        log_error "fapolicyd-cli could not trust $bin (exit $rc)"
        [ -z "$out" ] || printf '%s\n' "$out" | sed 's/^/  /'
        echo "  k3s cannot start until fapolicyd trusts it. As root:"
        fapolicyd_fix
        exit 1
    fi
    fapolicyd_reload fapolicyd_fix
}

# Reloads fapolicyd's rules and trust database, once for every rule file written before
# it; on failure prints fix $1 (a function) and stops.
fapolicyd_reload() {
    if ! k3s_root fapolicyd-cli --update >/dev/null 2>&1 || ! k3s_root fagenrules --load >/dev/null 2>&1 \
        || ! k3s_root systemctl restart fapolicyd; then
        log_error "fapolicyd did not reload its rules and trust database"
        echo "  Check journalctl -u fapolicyd, then, as root:"
        "$1"
        exit 1
    fi
    FAPOLICYD_RELOAD_PENDING=""
    host_prep_change "fapolicyd: reloaded (fapolicyd-cli --update, fagenrules --load, systemctl restart fapolicyd)"
}

# Puts source $1 in firewalld's trusted zone, in the runtime configuration or with
# $3 = --permanent the permanent one; $2 is the zone it is bound to now, if any.
trust_firewalld_source() {
    local verb=add where="${3:+permanent}"
    [ -z "$2" ] || verb=change
    # shellcheck disable=SC2086
    if k3s_root firewall-cmd $3 --zone=trusted --"$verb"-source="$1" >/dev/null 2>&1; then
        host_prep_change "firewalld: $1 in zone trusted (${where:-runtime}${2:+, moved from zone $2})"
    else
        log_warn "firewall-cmd ${3:+$3 }--zone=trusted --$verb-source=$1 failed"
    fi
}

# Opens https in firewalld zone $1, in the runtime configuration or with $2 = --permanent
# the permanent one, unless it accepts 443/tcp already.
open_firewalld_https() {
    # shellcheck disable=SC2086
    if zone_accepts "$1" $2 || k3s_root firewall-cmd $2 --zone="$1" --query-service=https >/dev/null 2>&1 \
        || k3s_root firewall-cmd $2 --zone="$1" --query-port=443/tcp >/dev/null 2>&1; then
        return 0
    fi
    local where=runtime
    [ -z "${2:-}" ] || where=permanent
    # shellcheck disable=SC2086
    if k3s_root firewall-cmd $2 --zone="$1" --add-service=https >/dev/null 2>&1; then
        host_prep_change "firewalld: service https in zone $1 ($where) for the SCIM Ingress"
    else
        log_warn "firewall-cmd ${2:+$2 }--zone=$1 --add-service=https failed"
    fi
}

# With firewalld running, trusts the pod and service networks (POD_NETWORK_CIDRS), in
# the permanent and the runtime configuration, and with --scim-host opens https in the
# default route's zone. Changes only what is missing.
prep_firewalld() {
    local AS_ROOT_SUDO="${AS_ROOT_SUDO:-}" cidr zone
    command -v firewall-cmd >/dev/null 2>&1 || return 0
    [ "$(k3s_root firewall-cmd --state 2>/dev/null || true)" = "running" ] || return 0
    [ "$(id -u)" -eq 0 ] || AS_ROOT_SUDO=true
    for cidr in $POD_NETWORK_CIDRS; do
        zone=$(k3s_root firewall-cmd --permanent --get-zone-of-source="$cidr" 2>/dev/null) || zone=""
        zone_accepts "$zone" --permanent || trust_firewalld_source "$cidr" "$zone" --permanent
        zone=$(k3s_root firewall-cmd --get-zone-of-source="$cidr" 2>/dev/null) || zone=""
        zone_accepts "$zone" || trust_firewalld_source "$cidr" "$zone"
    done
    [ -n "${MC_SCIM_HOST:-}" ] && product_has mc || return 0
    zone=$(default_route_zone k3s_root)
    if [ -z "$zone" ]; then
        log_warn "Could not find firewalld's zone for the default route: https for the SCIM Ingress is not opened"
        return 0
    fi
    open_firewalld_https "$zone" --permanent
    open_firewalld_https "$zone"
}

# =============================================================================
# klyro CLI: squad/install.sh from the Klyro CDN, run as the CLI user
# =============================================================================

SUBUID_FILE="/etc/subuid"
SUBGID_FILE="/etc/subgid"
# useradd's defaults (SUB_UID_MIN and SUB_UID_COUNT in /etc/login.defs).
SUBID_MIN=100000
SUBID_COUNT=65536
SUBID_LOCK="/run/klyro-subid.lock"
CLI_RUNTIME_BASE="/run/user"
CLI_LINGER_DIR="/var/lib/systemd/linger"
CLI_RUNTIME_WAIT=30
CLI_STD_PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

cli_wanted() {
    [ "${CLI_INSTALL:-}" != "off" ]
}

# Sets CLI_USER, CLI_UID, CLI_HOME and CLI_USER_SOURCE for the user the CLI is for:
# --cli-user, else SUDO_USER when running as root, else this user. Sets CLI_SKIP_REASON
# instead when root has neither. Fails, with CLI_ERROR, for a user that does not exist,
# is root, or whose home is not an absolute path without whitespace.
resolve_cli_user() {
    local name src entry
    CLI_USER="" CLI_UID="" CLI_HOME="" CLI_USER_SOURCE="" CLI_SKIP_REASON="" CLI_ERROR=""
    cli_wanted || return 0
    if [ -n "${CLI_USER_FLAG:-}" ]; then
        name="$CLI_USER_FLAG" src="--cli-user"
    elif [ "$(id -u)" -eq 0 ]; then
        name="${SUDO_USER:-}" src="SUDO_USER"
        if [ -z "$name" ] || [ "$name" = "root" ]; then
            CLI_SKIP_REASON="running as root, not through sudo: no user to install the klyro CLI for"
            return 0
        fi
    else
        name=$(id -un) src="the user running the installer"
    fi
    entry=$(getent passwd "$name" 2>/dev/null | head -n 1)
    if [ -z "$entry" ]; then
        CLI_ERROR="$src $name: no such user"
        return 1
    fi
    CLI_UID=$(printf '%s\n' "$entry" | cut -d: -f3)
    CLI_HOME=$(printf '%s\n' "$entry" | cut -d: -f6)
    if [ "$CLI_UID" = "0" ]; then
        CLI_ERROR="$src $name is root: the klyro CLI and rootless Docker run as a normal user"
        return 1
    fi
    case "$CLI_HOME" in
        *[[:space:]]*|"") CLI_ERROR="$src $name has a home directory with whitespace or none ($CLI_HOME)"; return 1 ;;
        /*) ;;
        *) CLI_ERROR="$src $name has no absolute home directory ($CLI_HOME)"; return 1 ;;
    esac
    CLI_HOME="${CLI_HOME%/}"
    CLI_USER="$name" CLI_USER_SOURCE="$src"
}

# resolve_cli_user for an install: it stops on a bad user, and the CLI is skipped with a
# warning when the installer does not run as root (the host prep needs root).
resolve_cli_install() {
    if ! resolve_cli_user; then
        log_error "$CLI_ERROR"
        echo "  Pass --cli-user <the user who will run klyro>, or leave cli out of --product (--product researcher,mc)."
        exit 1
    fi
    cli_wanted || return 0
    if [ -z "$CLI_SKIP_REASON" ] && [ "$(id -u)" -ne 0 ]; then
        CLI_SKIP_REASON="the installer is not running as root, which the klyro CLI's host prep needs"
    fi
    if [ -n "$CLI_SKIP_REASON" ] && [ "${CLI_INSTALL:-}" = "on" ]; then
        log_error "--product $PRODUCT_LABEL asks for the klyro CLI, but $CLI_SKIP_REASON"
        echo "  Run the installer with sudo as the user who will run klyro, or as root with --cli-user <name>."
        exit 1
    fi
    if [ -n "$CLI_SKIP_REASON" ]; then
        log_warn "klyro CLI skipped: $CLI_SKIP_REASON"
        echo "  To install it, re-run with sudo as the user who will run klyro, or as root with --cli-user <name>; --product researcher,mc leaves it out."
        CLI_USER=""
        return 0
    fi
    log_info "klyro CLI: for $CLI_USER ($CLI_USER_SOURCE), home $CLI_HOME"
}

# The klyro channel the env's CDN publishes: stable, staging or dev.
cli_channel() {
    case "$KLYRO_ENV" in
        dev) echo dev ;;
        staging) echo staging ;;
        *) echo stable ;;
    esac
}

squad_installer_url() {
    printf 'https://%s/squad/install.sh\n' "$KLYRO_CDN"
}

cli_runtime_dir() {
    printf '%s/%s\n' "$CLI_RUNTIME_BASE" "$CLI_UID"
}

# Prints squad/install.sh from the env's CDN along the --proxy route, the remaining
# arguments going to curl; KLYRO_SQUAD_INSTALLER, a local file, replaces the download.
# The proxy reaches curl as a config on stdin (-K -), never on a command line.
fetch_squad_installer() {
    if [ -n "${KLYRO_SQUAD_INSTALLER:-}" ]; then
        cat -- "$KLYRO_SQUAD_INSTALLER"
        return
    fi
    if [ -z "$PROXY_URL" ]; then
        curl -fsSL "$@" "$(squad_installer_url)" </dev/null
        return
    fi
    printf 'proxy = "%s"\nnoproxy = "%s"\n' "$(curl_config_escape "$PROXY_URL")" "$(curl_config_escape "$(node_no_proxy)")" \
        | curl -K - -fsSL "$@" "$(squad_installer_url)"
}

# $1 with backslashes and double quotes escaped for a quoted curl config value.
curl_config_escape() {
    printf '%s' "$1" | sed 's/[\\"]/\\&/g'
}

# $1 single-quoted for sh.
sh_quote() {
    printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

# export lines for the proxy squad runs with: --proxy (or the detected one) with
# node_no_proxy, else the shell's own proxy variables.
cli_proxy_exports() {
    local v val np
    if [ -n "$PROXY_URL" ]; then
        np=$(node_no_proxy)
        for v in HTTPS_PROXY https_proxy HTTP_PROXY http_proxy; do
            printf 'export %s=%s\n' "$v" "$(sh_quote "$PROXY_URL")"
        done
        printf 'export NO_PROXY=%s no_proxy=%s\n' "$(sh_quote "$np")" "$(sh_quote "$np")"
        return 0
    fi
    for v in HTTPS_PROXY https_proxy HTTP_PROXY http_proxy NO_PROXY no_proxy; do
        eval "val=\${$v:-}"
        [ -z "$val" ] || printf 'export %s=%s\n' "$v" "$(sh_quote "$val")"
    done
}

# Runs command $@ as CLI_USER (runuser as root, sudo -n runuser otherwise) with a clean
# environment: HOME, USER, LOGNAME, a system PATH, the env's KLYRO_CDN, KLYRO_API and
# KLYRO_CLI_CHANNEL, and XDG_RUNTIME_DIR when /run/user/<uid> exists. Leading NAME=value
# arguments are added to that environment.
cli_user_run() {
    local xdg
    xdg=$(cli_runtime_dir)
    [ ! -d "$xdg" ] || set -- "XDG_RUNTIME_DIR=$xdg" "$@"
    set -- env -i "HOME=$CLI_HOME" "USER=$CLI_USER" "LOGNAME=$CLI_USER" "PATH=$CLI_STD_PATH" \
        "KLYRO_CDN=https://$KLYRO_CDN" "KLYRO_API=$KLYRO_API_URL" "KLYRO_CLI_CHANNEL=$(cli_channel)" "$@"
    if [ "$CLI_USER" = "$(id -un)" ]; then
        "$@"
    elif [ "$(id -u)" -eq 0 ]; then
        runuser -u "$CLI_USER" -- "$@"
    else
        sudo -n runuser -u "$CLI_USER" -- "$@"
    fi
}

# Runs squad script $1 as CLI_USER, read by bash from stdin (no file for fapolicyd to
# judge) after the proxy's export lines (which may hold credentials, so they never reach
# a command line), with the further arguments: NAME=value ones for its environment, then
# its own.
cli_run_squad() {
    local script="$1"
    shift
    { cli_proxy_exports; printf '%s\n' "$script"; } | cli_user_run "$@"
}

# The fapolicyd rules that let CLI_USER run what squad installs, one per line.
cli_fapolicyd_rules() {
    local d
    for d in bin .local/bin .klyro; do
        printf 'allow perm=any all : dir=%s/%s/\n' "$CLI_HOME" "$d"
    done
}

cli_fapolicyd_file() {
    printf '%s/81-klyro-squad-%s.rules\n' "$FAPOLICYD_RULES_DIR" "$CLI_USER"
}

cli_fapolicyd_fix() {
    echo ""
    echo "cat > $(cli_fapolicyd_file) <<'EOF'"
    cli_fapolicyd_rules
    echo "EOF"
    echo "fagenrules --load; systemctl restart fapolicyd"
    echo ""
}

fapolicyd_active() {
    [ "$(systemctl is-active fapolicyd 2>/dev/null || true)" = "active" ]
}

# Prints the rules of cli_fapolicyd_rules missing from the CLI user's rule file.
cli_fapolicyd_missing() {
    local f
    f=$(cli_fapolicyd_file)
    cli_fapolicyd_rules | while IFS= read -r rule; do
        as_root grep -qxF -- "$rule" "$f" 2>/dev/null || printf '%s\n' "$rule"
    done
}

# Succeeds when every cli_fapolicyd_rules line is in fapolicyd's compiled rules, which
# fagenrules --load writes from rules.d: false when a run wrote them and stopped before
# reloading.
cli_fapolicyd_loaded() {
    cli_fapolicyd_rules | while IFS= read -r rule; do
        as_root grep -qxF -- "$rule" "$FAPOLICYD_COMPILED" 2>/dev/null || return 1
    done
}

# With fapolicyd active, adds the missing cli_fapolicyd_rules lines to the CLI user's
# rules.d file and marks fapolicyd for one reload (FAPOLICYD_RELOAD_PENDING), as it does
# for rules already there that fapolicyd has not loaded.
prep_cli_fapolicyd() {
    local f missing created=""
    fapolicyd_active || return 0
    f=$(cli_fapolicyd_file)
    if [ ! -d "$FAPOLICYD_RULES_DIR" ]; then
        log_warn "fapolicyd is active but $FAPOLICYD_RULES_DIR does not exist: $CLI_USER cannot run klyro or rootless Docker. As root, put these lines before the deny rules of /etc/fapolicyd/fapolicyd.rules, then restart fapolicyd:"
        cli_fapolicyd_rules | sed 's/^/  /'
        return 0
    fi
    missing=$(cli_fapolicyd_missing)
    if [ -z "$missing" ]; then
        cli_fapolicyd_loaded || FAPOLICYD_RELOAD_PENDING=true
        return 0
    fi
    [ -e "$f" ] || created=yes
    printf '%s\n' "$missing" >> "$f"
    [ -z "$created" ] || chmod 0644 "$f"
    FAPOLICYD_RELOAD_PENDING=true
    host_prep_change "fapolicyd: $f allows $(printf '%s\n' "$missing" | sed 's/.*dir=//' | tr '\n' ' ' | sed 's/ $//')"
}

# Succeeds when file $1 has a subordinate ID range for CLI_USER, as squad checks it.
cli_has_subids() {
    grep -q "^$CLI_USER:" "$1" 2>/dev/null
}

# The first subordinate ID past every range in SUBUID_FILE and SUBGID_FILE, at least
# SUBID_MIN: a range starting there is free in both.
next_free_subid() {
    cat "$SUBUID_FILE" "$SUBGID_FILE" 2>/dev/null | awk -F: -v min="$SUBID_MIN" '
        $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ && $2 + $3 > max { max = $2 + $3 }
        END { printf "%d\n", (max > min ? max : min) }'
}

# The subordinate ID range CLI_USER would get, as start-end.
cli_subid_range() {
    local start
    start=$(next_free_subid)
    printf '%s-%s\n' "$start" $((start + SUBID_COUNT - 1))
}

# Gives CLI_USER a subordinate UID and GID range (rootless Docker's user namespace) where
# it has none, holding SUBID_LOCK (flock) from the scan to the grant so that two
# installer runs never hand out the same range.
prep_cli_subids() {
    local rc=0 locked=""
    cli_has_subids "$SUBUID_FILE" && cli_has_subids "$SUBGID_FILE" && return 0
    if command -v flock >/dev/null 2>&1 && [ -d "${SUBID_LOCK%/*}" ]; then
        exec 9>>"$SUBID_LOCK"
        locked=yes
        flock -x 9 || true
    fi
    grant_cli_subids || rc=$?
    [ -z "$locked" ] || exec 9>&-
    return "$rc"
}

grant_cli_subids() {
    local range what=""
    cli_has_subids "$SUBUID_FILE" && cli_has_subids "$SUBGID_FILE" && return 0
    range=$(cli_subid_range)
    set --
    if ! cli_has_subids "$SUBUID_FILE"; then
        set -- --add-subuids "$range"
        what="$SUBUID_FILE"
    fi
    if ! cli_has_subids "$SUBGID_FILE"; then
        set -- "$@" --add-subgids "$range"
        what="${what:+$what and }$SUBGID_FILE"
    fi
    if ! usermod "$@" "$CLI_USER"; then
        log_error "usermod $* $CLI_USER failed"
        echo "  rootless Docker needs a subordinate ID range for $CLI_USER in $SUBUID_FILE and $SUBGID_FILE."
        return 1
    fi
    host_prep_change "subordinate IDs: $range for $CLI_USER in $what"
}

cli_lingers() {
    [ -e "$CLI_LINGER_DIR/$CLI_USER" ]
}

# Turns on lingering for CLI_USER, so systemd keeps /run/user/<uid> (its XDG_RUNTIME_DIR)
# without a login session and its rootless Docker keeps running after logout, then waits
# for that directory.
prep_cli_linger() {
    local dir tries=0
    if ! command -v loginctl >/dev/null 2>&1; then
        log_warn "loginctl not found (no systemd-logind): $CLI_USER gets no XDG_RUNTIME_DIR outside a login session"
        return 0
    fi
    if ! cli_lingers; then
        if ! loginctl enable-linger "$CLI_USER"; then
            log_error "loginctl enable-linger $CLI_USER failed"
            return 1
        fi
        host_prep_change "loginctl enable-linger $CLI_USER ($(cli_runtime_dir) kept without a login session)"
    fi
    dir=$(cli_runtime_dir)
    until [ -d "$dir" ]; do
        tries=$((tries + 1))
        if [ "$tries" -gt "$CLI_RUNTIME_WAIT" ]; then
            log_error "$dir did not appear within ${CLI_RUNTIME_WAIT}s of loginctl enable-linger $CLI_USER"
            echo "  Check: systemctl status user@$CLI_UID.service"
            return 1
        fi
        sleep 1
    done
}

# The command that re-runs only the CLI step of this install.
cli_rerun_command() {
    local args="--product cli"
    [ -z "$KLYRO_ENV" ] || [ "$KLYRO_ENV" = production ] || args="$args --env $KLYRO_ENV"
    [ -z "$CLI_USER_FLAG" ] || args="$args --cli-user $CLI_USER_FLAG"
    if [ -n "$PROXY_URL" ] && [ -z "$PROXY_AUTO" ]; then
        args="$args --proxy $(pf_redact_url "$PROXY_URL")"
        [ -z "$NO_PROXY_EXTRA" ] || args="$args --no-proxy $NO_PROXY_EXTRA"
    fi
    printf 'curl -fsSL https://get.klyro.security/install.sh | sudo bash -s -- %s\n' "$args"
    [ "$(pf_redact_url "$PROXY_URL")" = "$PROXY_URL" ] || [ -n "$PROXY_AUTO" ] \
        || echo "      (put the proxy's user and password back in place of ***)"
}

# Before anything changes: fetches squad/install.sh into CLI_SQUAD_SCRIPT and runs its
# --check as CLI_USER, with KLYRO_SQUAD_ADMIN_PREP=1 (the items the host prep sets up
# are info, not FAIL). Stops the install when the check fails.
check_cli() {
    local out rc=0
    [ -n "$CLI_USER" ] || return 0
    log_info "Checking this host for the klyro CLI ($(squad_installer_url) --check, as $CLI_USER)..."
    if ! CLI_SQUAD_SCRIPT=$(fetch_squad_installer --retry 3) || [ -z "$CLI_SQUAD_SCRIPT" ]; then
        log_error "Failed to download $(squad_installer_url), or it is empty"
        echo "  Ensure this host reaches https://$KLYRO_CDN${PROXY_URL:+ through the proxy}, or leave cli out of --product (--product researcher,mc)."
        exit 1
    fi
    out=$(cli_run_squad "$CLI_SQUAD_SCRIPT" KLYRO_SQUAD_ADMIN_PREP=1 bash -s -- --check 2>&1) || rc=$?
    printf '%s\n' "$out" | sed 's/^/  /'
    if [ "$rc" -ne 0 ]; then
        log_error "This host is not ready for the klyro CLI (squad --check exit $rc): nothing was installed"
        echo "  Fix the FAIL lines above, or leave cli out of --product (--product researcher,mc) to install without it."
        exit 1
    fi
    log_success "Host ready for the klyro CLI"
}

# The root-only host changes squad cannot make for CLI_USER.
prep_cli_host() {
    [ -n "$CLI_USER" ] || return 0
    prep_cli_fapolicyd
    if ! prep_cli_subids || ! prep_cli_linger; then
        [ "$PRODUCT" = "none" ] || echo "  Nothing else was installed. Fix it, or leave cli out of --product (--product researcher,mc)."
        exit 1
    fi
}

# Prints "<version> at <path>" of the klyro CLI_USER's PATH finds, squad's dirs first.
cli_installed_klyro() {
    # shellcheck disable=SC2016
    cli_user_run "PATH=$CLI_HOME/bin:$CLI_HOME/.local/bin:$CLI_STD_PATH" sh -c \
        'p=$(command -v klyro) && printf "%s at %s\n" "$("$p" version 2>/dev/null | awk "NR == 1 { print \$2 }")" "$p"' 2>/dev/null || true
}

# Reloads fapolicyd for the CLI rules when nothing has since, then runs squad/install.sh
# as CLI_USER, with KLYRO_SQUAD_ADMIN_PREP=1: an item the host prep should have set up
# fails it. On failure the cluster products stay installed: it says so, and how to
# re-run only this step, and stops.
install_cli() {
    local rc=0 klyro
    [ -n "$CLI_USER" ] || return 0
    [ "$FAPOLICYD_RELOAD_PENDING" != "true" ] || fapolicyd_reload cli_fapolicyd_fix
    log_info "Running $(squad_installer_url) as $CLI_USER..."
    cli_run_squad "$CLI_SQUAD_SCRIPT" KLYRO_SQUAD_ADMIN_PREP=1 "TMPDIR=$CLI_HOME/.klyro" bash -s || rc=$?
    if [ "$rc" -ne 0 ]; then
        log_error "The klyro CLI install failed for $CLI_USER (squad/install.sh exit $rc; its output is above)"
        [ "$PRODUCT" = "none" ] || echo "  Everything else is installed and verified; only the CLI step failed."
        echo "  To re-run only the CLI step, once the cause is fixed:"
        echo "    $(cli_rerun_command)"
        exit 1
    fi
    klyro=$(cli_installed_klyro)
    case "$klyro" in
        ""|" at "*)
            log_error "squad/install.sh exited 0, but $CLI_USER has no klyro that reports its version (${klyro:-none on PATH})"
            [ "$PRODUCT" = "none" ] || echo "  Everything else is installed and verified; only the CLI step failed."
            echo "  To re-run only the CLI step:"
            echo "    $(cli_rerun_command)"
            exit 1
            ;;
    esac
    CLI_SUMMARY="  klyro CLI:  ${GREEN}${klyro}${NC} for $CLI_USER
  Next step:  as $CLI_USER, run: klyro login --api $KLYRO_API_URL"
    log_success "klyro CLI installed for $CLI_USER: $klyro"
}

print_host_prep_summary() {
    [ -n "$HOST_PREP_CHANGES" ] || return 0
    echo "  Host prep (the installer changed this host):"
    printf '%s\n' "$HOST_PREP_CHANGES" | sed 's/^/    /'
    echo ""
}

print_cli_summary() {
    if [ -n "$CLI_SUMMARY" ]; then
        printf '%s\n' "$CLI_SUMMARY"
        echo ""
    elif [ -n "$CLI_SKIP_REASON" ]; then
        echo "  klyro CLI:  ${YELLOW}skipped ($CLI_SKIP_REASON)${NC}"
        echo "              to add it: $(cli_rerun_command)"
        echo ""
    fi
}

# --product cli: the klyro CLI's host prep and squad install, nothing else. No token is
# redeemed and no cluster is touched, so a token and --bootstrap are ignored.
main_cli_only() {
    show_banner
    log_info "Components: the klyro CLI"
    [ -z "$INSTALL_TOKEN" ] || log_info "--product cli: the install token is not used (nothing is redeemed)"
    [ "$bootstrap_cluster" != "true" ] || log_warn "--product cli: --bootstrap does nothing (k3s is only for the Researcher and MC)"
    resolve_cli_install
    STEP_TOTAL=2
    STEP_CURRENT=1
    begin_step "Preparing this host for the klyro CLI"
    check_cli
    prep_cli_host
    begin_step "Installing the klyro CLI for $CLI_USER"
    install_cli
    echo ""
    print_cli_summary
    print_host_prep_summary
}

# k3s bundles both kubectl AND a Helm controller, so this is the only prerequisite
# install needed: on a bare box the customer needs just curl + sh. Everything comes
# from *.klyro.security: the k3s installer and binary from the Klyro CDN, k3s-selinux
# from its rpm.rancher.io mirror, the system images from the Klyro registry.
bootstrap_k3s_cluster() {
    log_step "No Kubernetes cluster detected — bootstrapping k3s"
    if command -v k3s >/dev/null 2>&1 && [ -f /etc/rancher/k3s/k3s.yaml ]; then
        log_info "k3s already installed"
        if [ -n "$K3S_DATA_DIR" ]; then
            log_warn "--data-dir applies only to a new k3s install; the existing k3s keeps its data dir"
        fi
    else
        [ "$(id -u)" -eq 0 ] || require_root_or_sudo
        log_info "Installing k3s (brings up Kubernetes + kubectl)..."
        # Download, then run: NOT `curl … | sh -`. A pipeline reports the status of
        # its LAST command, so a failed download was masked by the no-op `sh` that
        # read the empty pipe, and the real error only surfaced ~3 minutes later as a
        # bogus "node did not become Ready". On a bare VM the download is the single
        # most likely thing to fail, which is exactly what --bootstrap targets.
        # Cleanup is an explicit rm on every path, deliberately not an EXIT trap:
        # this runs before fetch_credentials and install_helm_chart register theirs,
        # and a third EXIT trap would just be silently clobbered by them (KAN-694).
        local K3S_INSTALLER K3S_RC k3s_installer k3s_service k3s_start=false fapolicyd_prep=false
        if [ -n "$K3S_DATA_DIR" ]; then
            INSTALL_K3S_EXEC="${INSTALL_K3S_EXEC:+$INSTALL_K3S_EXEC }--data-dir=$K3S_DATA_DIR"
            export INSTALL_K3S_EXEC
            log_info "k3s data dir: $K3S_DATA_DIR"
        fi
        k3s_installer=$(k3s_installer_url)
        K3S_INSTALLER=$(mktemp)
        if ! curl -sfL "$k3s_installer" -o "$K3S_INSTALLER"; then
            rm -f "$K3S_INSTALLER"
            log_error "Failed to download the k3s installer from $k3s_installer"
            echo "  Ensure the host can reach https://$KLYRO_CDN (directly, or through the shell's HTTPS_PROXY)."
            exit 1
        fi
        INSTALL_K3S_ARTIFACT_URL=$(k3s_artifact_url)
        INSTALL_K3S_VERSION=$(k3s_version)
        export INSTALL_K3S_ARTIFACT_URL INSTALL_K3S_VERSION
        log_info "k3s $INSTALL_K3S_VERSION from $INSTALL_K3S_ARTIFACT_URL"
        write_k3s_registries
        install_k3s_selinux
        prep_firewalld
        [ "$(systemctl is-active fapolicyd 2>/dev/null || true)" != "active" ] || fapolicyd_prep=true
        if { [ "$K3S_SELINUX_RELABEL" = true ] || [ "$fapolicyd_prep" = true ]; } && [ "${INSTALL_K3S_SKIP_START:-}" != true ]; then
            INSTALL_K3S_SKIP_START=true
            export INSTALL_K3S_SKIP_START
            k3s_start=true
        fi
        K3S_RC=0
        k3s_proxy_run sh "$K3S_INSTALLER" || K3S_RC=$?
        rm -f "$K3S_INSTALLER"
        if [ "$K3S_RC" -ne 0 ]; then
            log_error "k3s installation failed (exit $K3S_RC)"
            echo "  The k3s installer output is above."
            exit 1
        fi
        if [ "$K3S_SELINUX_RELABEL" = true ]; then
            label_k3s_binary
        fi
        if [ "$fapolicyd_prep" = true ]; then
            prep_fapolicyd
        fi
        if [ "$k3s_start" = true ]; then
            k3s_service="k3s${INSTALL_K3S_NAME:+-$INSTALL_K3S_NAME}"
            log_info "Starting $k3s_service..."
            if ! k3s_root systemctl restart "$k3s_service"; then
                log_error "k3s did not start (systemctl restart $k3s_service)"
                echo "  Check: journalctl -u $k3s_service"
                exit 1
            fi
        fi
    fi
    use_k3s_kubeconfig
    export PATH="/usr/local/bin:$PATH"
    log_info "Waiting for the k3s node to become Ready..."
    local tries=0 nodes_out=""
    until nodes_out=$(kubectl get nodes 2>&1) && printf '%s\n' "$nodes_out" | grep -q ' Ready'; do
        tries=$((tries + 1))
        if [ "$tries" -gt 60 ]; then
            check_fapolicyd
            log_error "k3s node did not become Ready in time"
            echo "  Last kubectl get nodes output:"
            printf '%s\n' "$nodes_out" | sed 's/^/    /'
            exit 1
        fi
        sleep 3
    done
    USE_HELM_CONTROLLER=true
    log_success "k3s cluster ready — kubectl + Helm controller bundled (no separate Helm binary needed)"
}

K3S_DATA_DIR_DEFAULT="/var/lib/rancher/k3s"
K3S_CONFIG_DEFAULT="/etc/rancher/k3s/config.yaml"
# The config file a new k3s install reads; an installed k3s uses its own service settings.
K3S_CONFIG_FILE="${K3S_CONFIG_FILE:-$K3S_CONFIG_DEFAULT}"
K3S_SERVICE_FILES="/etc/systemd/system/k3s.service /etc/init.d/k3s"
# The env file the k3s openrc script sources; a systemd unit lists its own.
K3S_OPENRC_ENV_FILE="/etc/rancher/k3s/k3s.env"
DISK_FAIL_GIB=30
DISK_WARN_GIB=50
INODE_FAIL_PCT=5
# k3s's default pod and service networks: firewalld must trust them on a node.
POD_NETWORK_CIDRS="10.42.0.0/16 10.43.0.0/16"
FAPOLICYD_RULES_DIR="/etc/fapolicyd/rules.d"
FAPOLICYD_RULES="$FAPOLICYD_RULES_DIR /etc/fapolicyd/fapolicyd.rules"
FAPOLICYD_CONF="/etc/fapolicyd/fapolicyd.conf"
FAPOLICYD_COMPILED="/etc/fapolicyd/compiled.rules"

nearest_existing_dir() {
    local p="$1"
    while [ ! -d "$p" ] && [ "$p" != "/" ] && [ -n "$p" ]; do
        p=$(dirname "$p")
    done
    printf '%s\n' "${p:-/}"
}

# The top-level key $1 of one k3s YAML config file $2, quotes and inline comment
# removed. A later key in the file wins, as in k3s.
yaml_key() {
    awk -v key="$1:" '
        index($0, key) == 1 {
            v = substr($0, length(key) + 1)
            sub(/^[ \t]*/, "", v)
            q = substr(v, 1, 1)
            if (q == "\"" || q == "\047") {
                v = substr(v, 2)
                i = index(v, q)
                if (i > 0) v = substr(v, 1, i - 1)
            } else {
                sub(/^#.*$/, "", v)
                sub(/[ \t]+#.*$/, "", v)
                sub(/[ \t]+$/, "", v)
            }
            d = v
        }
        END { if (d != "") print d }
    ' "$2"
}

# The key $1 from the config file ($2, default K3S_CONFIG_FILE) and then its .d/*.yaml
# drop-ins in name order; the last file that sets it wins, as in k3s.
config_value() {
    local cfg="${2:-$K3S_CONFIG_FILE}" f v d=""
    for f in "$cfg" "$cfg".d/*.yaml; do
        [ -f "$f" ] || continue
        v=$(yaml_key "$1" "$f")
        if [ -n "$v" ]; then
            d="$v"
        fi
    done
    if [ -n "$d" ]; then
        printf '%s\n' "$d"
    fi
    return 0
}

# The variable $2 from the k3s service environment files listed one per line in
# $1, read in that order; the last assignment wins, as in systemd.
service_env() {
    printf '%s\n' "$1" | while IFS= read -r ef; do
        if [ -n "$ef" ] && [ -f "$ef" ]; then
            sed -n "s/^[[:space:]]*\(export[[:space:]]\{1,\}\)\{0,1\}$2=//p" "$ef"
        fi
    done | tail -n 1 | tr -d "'\"" | sed 's/[[:space:]]*$//'
}

# The EnvironmentFile= paths of systemd unit $1 in order, %N expanded (the k3s
# install script lists /etc/default/%N, /etc/sysconfig/%N, then <unit>.env).
unit_env_files() {
    local name
    name=$(basename "$1" .service)
    sed -n 's/^[[:space:]]*EnvironmentFile=-\{0,1\}//p' "$1" | sed "s|%N|$name|g"
}

# The value of the k3s flag --$1 in the arguments read from stdin; the last one
# wins, as in k3s. Comment lines are skipped and line continuations joined;
# single-quoted, double-quoted and backslash-escaped words keep their spaces, as
# systemd and sh read them. With $2 = noquote, double quotes are dropped first:
# the openrc script wraps its whole argument list in one double-quoted string.
k3s_arg() {
    awk -v want="--$1" -v dq="${2:-}" '
        /^[ \t]*#/ { next }
        { s = s $0 "\n" }
        END {
            gsub(/\\\n/, " ", s)
            if (dq == "noquote") gsub(/"/, "", s)
            n = 0; tok = ""; intok = 0; q = ""; len = length(s)
            for (i = 1; i <= len; i++) {
                c = substr(s, i, 1)
                if (q != "") { if (c == q) q = ""; else tok = tok c; continue }
                if (c == "\"" || c == "\047") { q = c; intok = 1; continue }
                if (c == "\\" && i < len) { i++; tok = tok substr(s, i, 1); intok = 1; continue }
                if (c == " " || c == "\t" || c == "\n") {
                    if (intok) { a[++n] = tok; tok = ""; intok = 0 }
                    continue
                }
                tok = tok c; intok = 1
            }
            if (intok) a[++n] = tok
            for (j = 1; j <= n; j++) {
                if (index(a[j], want "=") == 1) d = substr(a[j], length(want) + 2)
                else if (a[j] == want && j < n) d = a[j + 1]
            }
            if (d != "") print d
        }'
}

# The data dir a new k3s install from bootstrap_k3s_cluster will use: the
# installer's --data-dir (appended last to INSTALL_K3S_EXEC), a --data-dir already
# in INSTALL_K3S_EXEC, the config file (--config in INSTALL_K3S_EXEC, else
# K3S_CONFIG_FILE) and its drop-ins, or the default.
new_k3s_data_dir() {
    local d="$K3S_DATA_DIR"
    [ -n "$d" ] || d=$(printf '%s\n' "${INSTALL_K3S_EXEC:-}" | k3s_arg data-dir)
    [ -n "$d" ] || d=$(config_value data-dir "$(printf '%s\n' "${INSTALL_K3S_EXEC:-}" | k3s_arg config)")
    printf '%s\n' "${d:-$K3S_DATA_DIR_DEFAULT}"
}

# The data dir of a k3s installed on this host, or nothing when k3s is not
# installed here (no service file). Precedence follows k3s: a --data-dir in the
# service arguments, then the config files (k3s turns them into arguments), then
# K3S_DATA_DIR from the service environment, then the default. The config file is
# the service's --config, else its K3S_CONFIG_FILE, else the default path; never
# the caller's K3S_CONFIG_FILE.
installed_k3s_data_dir() {
    local f d mode envf cfg=""
    for f in $K3S_SERVICE_FILES; do
        [ -f "$f" ] || continue
        case "$f" in
            *.service) mode="" envf=$(unit_env_files "$f") ;;
            *) mode=noquote envf="$K3S_OPENRC_ENV_FILE" ;;
        esac
        d=$(k3s_arg data-dir "$mode" < "$f")
        if [ -n "$d" ]; then
            printf '%s\n' "$d"
            return 0
        fi
        cfg=$(k3s_arg config "$mode" < "$f")
        [ -n "$cfg" ] || cfg=$(service_env "$envf" K3S_CONFIG_FILE)
        d=$(config_value data-dir "${cfg:-$K3S_CONFIG_DEFAULT}")
        [ -n "$d" ] || d=$(service_env "$envf" K3S_DATA_DIR)
        printf '%s\n' "${d:-$K3S_DATA_DIR_DEFAULT}"
        return 0
    done
    return 0
}

disk_check_fail() {
    log_error "$1"
    echo "  The k3s data dir holds every container image and every local-path volume (Postgres, Temporal,"
    echo "  MC files and backups); local-path does not enforce PVC sizes. A full disk evicts pods cluster-wide."
    echo "  Sizing: docs/INSTALL.md §1 (Researcher ~20 GiB, with the MC and its backups ~60 GiB)."
    echo "  Free space or grow the volume, or with --bootstrap put k3s on a bigger disk: --data-dir <path>."
    echo "  To install anyway: re-run with --skip-disk-check"
    exit 1
}

# Sets EV_STATUS (ok, warn, fail, or skip when this disk is not the cluster's), EV_DETAIL
# and EV_FIX for the free space and inodes of the k3s data dir; with $1 = install, the
# data dir --bootstrap will use.
eval_disk_space() {
    local dir target avail_kb avail_gib inode_line inodes ifree ifree_pct
    EV_FIX="Free space or grow the volume, or with --bootstrap put k3s on a bigger disk: --data-dir <path> (sizing: docs/INSTALL.md §1)"
    if [ "$skip_disk_check" = "true" ]; then
        EV_STATUS=warn EV_DETAIL="Disk check skipped (--skip-disk-check)" EV_FIX="re-run without --skip-disk-check to check the disk"
        return 0
    fi
    if [ "${1:-}" = "install" ]; then
        # Same test as bootstrap_k3s_cluster: reuse an existing k3s, or install one.
        dir=""
        if command -v k3s >/dev/null 2>&1 && [ -f /etc/rancher/k3s/k3s.yaml ]; then
            dir=$(installed_k3s_data_dir)
        fi
        [ -n "$dir" ] || dir=$(new_k3s_data_dir)
    else
        dir=$(installed_k3s_data_dir)
        if [ -z "$dir" ]; then
            # No k3s on this host: a reachable cluster is remote, and this disk is not its.
            EV_STATUS=skip EV_DETAIL="Disk check skipped: k3s is not installed on this host; size the cluster's nodes from docs/INSTALL.md §1"
            return 0
        fi
    fi
    if [ "${1:-}" != "install" ] && [ ! -d "$dir" ]; then
        EV_STATUS=skip EV_DETAIL="Disk check skipped: no k3s data dir at $dir on this host; size the cluster's nodes from docs/INSTALL.md §1"
        return 0
    fi
    target=$(nearest_existing_dir "$dir")
    avail_kb=$(df -Pk "$target" 2>/dev/null | awk 'NR==2 {print $4}')
    case "$avail_kb" in
        ''|*[!0-9]*)
            EV_STATUS=warn EV_DETAIL="Disk check skipped: could not read free space of $target" EV_FIX="check that df -Pk $target works on this host"
            return 0
            ;;
    esac
    avail_gib=$((avail_kb / 1048576))
    if [ "$avail_gib" -lt "$DISK_FAIL_GIB" ]; then
        EV_STATUS=fail EV_DETAIL="Not enough disk for the k3s data dir $dir: ${avail_gib} GiB free on $target, at least ${DISK_FAIL_GIB} GiB required"
        return 0
    fi
    inode_line=$(df -Pi "$target" 2>/dev/null | awk 'NR==2 {print $2, $4}')
    inodes=${inode_line% *}
    ifree=${inode_line#* }
    case "$inodes$ifree" in
        ''|*[!0-9]*) ;;
        *)
            if [ "$inodes" -gt 0 ]; then
                ifree_pct=$((ifree * 100 / inodes))
                if [ "$ifree_pct" -lt "$INODE_FAIL_PCT" ]; then
                    EV_STATUS=fail EV_DETAIL="Not enough inodes for the k3s data dir $dir: ${ifree_pct}% free on $target, at least ${INODE_FAIL_PCT}% required"
                    return 0
                fi
            fi
            ;;
    esac
    if [ "$avail_gib" -lt "$DISK_WARN_GIB" ]; then
        EV_STATUS=warn EV_DETAIL="Low disk for the k3s data dir $dir: ${avail_gib} GiB free on $target; ${DISK_WARN_GIB} GiB recommended (docs/INSTALL.md §1)"
        return 0
    fi
    EV_STATUS=ok EV_DETAIL="Disk: ${avail_gib} GiB free for the k3s data dir $dir" EV_FIX=""
}

check_disk_space() {
    eval_disk_space "$@"
    case "$EV_STATUS" in
        fail) disk_check_fail "$EV_DETAIL" ;;
        warn) log_warn "$EV_DETAIL" ;;
        skip) log_info "$EV_DETAIL" ;;
        *) log_success "$EV_DETAIL" ;;
    esac
}

# Prints the fapolicyd rule file and commands that let k3s run its unpacked binaries.
fapolicyd_fix() {
    echo ""
    echo "cat > /etc/fapolicyd/rules.d/80-k3s.rules <<'EOF'"
    echo "allow perm=any all : dir=/var/lib/rancher/"
    echo "allow perm=any all : dir=/run/k3s/"
    echo "allow perm=any all : dir=/var/lib/kubelet/"
    echo "allow perm=any all : dir=/opt/cni/"
    echo "EOF"
    echo "fapolicyd-cli --file add /usr/local/bin/k3s --trust-file k3s"
    echo "fapolicyd-cli --update; fagenrules --load; systemctl restart fapolicyd; systemctl restart k3s"
    echo ""
    echo "  The installer changes fapolicyd only when --bootstrap installs k3s on this host. See docs/INSTALL.md, Pre-install checklist: RHEL / STIG hosts."
}

# fapolicyd_fix as one line of shell, for the preflight report.
FAPOLICYD_FIX_LINE="as root: printf '%s\\n' 'allow perm=any all : dir=/var/lib/rancher/' 'allow perm=any all : dir=/run/k3s/' 'allow perm=any all : dir=/var/lib/kubelet/' 'allow perm=any all : dir=/opt/cni/' > /etc/fapolicyd/rules.d/80-k3s.rules; if [ -e /usr/local/bin/k3s ]; then fapolicyd-cli --file add /usr/local/bin/k3s --trust-file k3s; fi; fapolicyd-cli --update; fagenrules --load; systemctl restart fapolicyd; if [ -e /usr/local/bin/k3s ]; then systemctl restart k3s; fi (on a host without k3s yet, run this line again once k3s is installed). See docs/INSTALL.md, Pre-install checklist: RHEL / STIG hosts."

# On a node whose k3s is installed but not running, with fapolicyd active and the cluster
# unreachable (a reachable one is not this k3s): EV_STATUS fail when the k3s journal shows
# fapolicyd denying its binaries, warn when no fapolicyd rule allows k3s's data dir, and
# skip when the rules cannot be read (needs root, or AS_ROOT_SUDO). A running k3s is
# left alone. With PF_ASSUME_NODE=true, a host without k3s is judged as the node k3s will
# be installed on. Never changes fapolicyd.
eval_fapolicyd() {
    local f
    EV_STATUS=ok EV_FIX=""
    if [ "$(systemctl is-active fapolicyd 2>/dev/null || true)" != "active" ]; then
        EV_DETAIL="not active"
        return 0
    fi
    if [ "$(systemctl show -p LoadState --value k3s 2>/dev/null || true)" = "loaded" ]; then
        if [ "$(systemctl is-active k3s 2>/dev/null || true)" = "active" ]; then
            EV_DETAIL="active; k3s is running"
            return 0
        fi
        if kubectl cluster-info --request-timeout=10s >/dev/null 2>&1; then
            EV_DETAIL="active; the cluster in use is reachable"
            return 0
        fi
        if [ "${PF_NOROOT:-}" = "true" ]; then
            EV_STATUS=skip EV_DETAIL="not verified (needs root)"
            return 0
        fi
        if as_root journalctl -u k3s -n 50 --no-pager 2>/dev/null | grep -q 'operation not permitted'; then
            EV_STATUS=fail EV_FIX="$FAPOLICYD_FIX_LINE"
            EV_DETAIL="k3s is not running: fapolicyd denies its binaries (operation not permitted in journalctl -u k3s)"
            return 0
        fi
    elif [ "${PF_ASSUME_NODE:-}" != "true" ]; then
        EV_DETAIL="active; no k3s on this host"
        return 0
    fi
    if [ "${PF_NOROOT:-}" = "true" ]; then
        EV_STATUS=skip EV_DETAIL="not verified (needs root)"
        return 0
    fi
    if [ "${AS_ROOT_SUDO:-}" != "true" ]; then
        for f in $FAPOLICYD_RULES; do
            if [ -e "$f" ] && [ ! -r "$f" ]; then
                EV_STATUS=skip EV_DETAIL="not verified (needs root)"
                return 0
            fi
        done
    fi
    # shellcheck disable=SC2086
    if ! as_root grep -Ersq '^[[:space:]]*allow[[:space:]].*dir=/var/lib/rancher/' $FAPOLICYD_RULES; then
        EV_STATUS=warn EV_FIX="$FAPOLICYD_FIX_LINE"
        EV_DETAIL="fapolicyd is active and no rule allows /var/lib/rancher/: k3s cannot run the binaries it unpacks there"
        return 0
    fi
    EV_DETAIL="a rule allows /var/lib/rancher/"
}

check_fapolicyd() {
    eval_fapolicyd
    case "$EV_STATUS" in
        fail)
            log_error "$EV_DETAIL"
            echo "  The install cannot succeed until k3s runs. Allow k3s in fapolicyd, as root:"
            fapolicyd_fix
            exit 1
            ;;
        warn)
            log_warn "$EV_DETAIL. To allow it, as root:"
            fapolicyd_fix
            ;;
    esac
}

check_prerequisites() {
    log_info "Checking prerequisites..."

    if ! command -v curl >/dev/null 2>&1; then
        log_error "curl not found"
        echo "  Install: https://curl.se/download.html"
        exit 1
    fi

    if [ "$bootstrap_cluster" = "true" ]; then
        if command -v kubectl >/dev/null 2>&1 && kubectl cluster-info >/dev/null 2>&1; then
            log_success "Existing Kubernetes cluster detected — using it"
            if [ -n "$K3S_DATA_DIR" ]; then
                log_warn "--data-dir applies only when --bootstrap installs k3s; the existing cluster keeps its data dir"
            fi
            check_disk_space
            # Pre-existing k3s: prefer the controller, so a re-run does not require
            # a helm binary that was never installed.
            if kubectl get crd helmcharts.helm.cattle.io >/dev/null 2>&1; then
                USE_HELM_CONTROLLER=true
            fi
        else
            check_disk_space install
            bootstrap_k3s_cluster
        fi
    else
        check_disk_space
    fi

    MISSING=0
    check_command "kubectl" "https://kubernetes.io/docs/tasks/tools/" || MISSING=1
    if [ "$USE_HELM_CONTROLLER" != "true" ]; then
        check_command "helm" "https://helm.sh/docs/intro/install/" || MISSING=1
    fi

    if [ "$MISSING" -eq 1 ]; then
        echo ""
        log_error "Missing required tools. Please install them and try again."
        if [ "$bootstrap_cluster" != "true" ]; then
            echo "  Tip: re-run with --bootstrap to auto-install a k3s cluster (needs only curl + sh)."
        fi
        exit 1
    fi
    log_success "Required tools installed"
    check_fapolicyd

    log_info "Checking Kubernetes connectivity..."
    if ! kubectl cluster-info >/dev/null 2>&1; then
        log_error "Cannot connect to Kubernetes cluster"
        echo ""
        echo "Please ensure:"
        echo "  - You have a valid kubeconfig (~/.kube/config)"
        echo "  - Your cluster is running and accessible"
        echo "  - Run: kubectl cluster-info"
        echo "  - Or re-run with --bootstrap to auto-install a k3s cluster"
        exit 1
    fi
    log_success "Kubernetes cluster accessible"

    log_info "Checking RBAC permissions..."
    if ! kubectl auth can-i create namespace >/dev/null 2>&1; then
        log_error "Insufficient permissions to create namespace"
        echo ""
        echo "The installer needs cluster-admin or equivalent permissions."
        exit 1
    fi

    if ! kubectl auth can-i create secret --namespace="$NAMESPACE" >/dev/null 2>&1; then
        log_error "Insufficient permissions to create secrets"
        exit 1
    fi
    log_success "RBAC permissions verified"

    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        log_success "Chart install: k3s Helm controller (no Helm binary required)"
    else
        log_info "Checking Helm version..."
        HELM_VERSION=$(helm version --short 2>/dev/null | grep -oE 'v[0-9]+\.[0-9]+' | head -1)
        HELM_MAJOR=$(printf '%s\n' "$HELM_VERSION" | cut -d. -f1 | tr -d 'v')
        if [ "$HELM_MAJOR" -lt 3 ]; then
            log_error "Helm 3.x required (found: $HELM_VERSION)"
            exit 1
        fi
        log_success "Helm version: $HELM_VERSION"
    fi
    check_pod_network_firewall
}

# =============================================================================
# Token Validation & Credential Fetch
# =============================================================================

GHCR_REGISTRY="ghcr.io/klyrohq"
KLYRO_REGISTRY=""        # registry.<env>.klyro.security (pull-through cache); set in apply_env_defaults
LLM_GATEWAY_URL=""        # llm.<env>.klyro.security egress gateway; set in apply_env_defaults
KLYRO_CDN=""             # cdn[.<env>].klyro.security assets CDN (k3s for --bootstrap); set in apply_env_defaults
REGISTRY_PREFIX=""       # "${KLYRO_REGISTRY}/" for install (empty in --local)
LOCAL_REGISTRY="localhost:5000"
K3D_REGISTRY="klyro-registry:5000"
LOCAL_IMAGE="localhost:5000/klyro-agent:dev"
GRPC_ENDPOINT="grpc.klyro.security:443"
json_value() {
    # printf '%s\n', not echo: dash's echo interprets backslash escapes while bash's
    # does not, so `echo` would silently corrupt any credential containing a JSON
    # escape (\\, \n, \/, \uXXXX) on the piped-sh path — e.g. "kat_a\\nb" would come
    # back as "kat_a\nb", and the agent would register with a wrong access token with
    # no error surfacing anywhere. printf '%s\n' is byte-identical under bash.
    printf '%s\n' "$1" | grep -o "\"$2\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" | sed "s/\"$2\"[[:space:]]*:[[:space:]]*\"//" | sed 's/"$//'
}

# redact_json prints an API response with the value of every field whose name
# looks secret (…secret…, …token…, …key…, …password…) replaced by "<redacted>",
# so KLYRO_DEBUG output and error dumps never echo credentials.
redact_json() {
    printf '%s\n' "$1" | sed -E 's/"([A-Za-z0-9_]*([Ss][Ee][Cc][Rr][Ee][Tt]|[Tt][Oo][Kk][Ee][Nn]|[Kk][Ee][Yy]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd])[A-Za-z0-9_]*)"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"/"\1":"<redacted>"/g'
}

# mask_token prints an install token with everything after its "inst_" prefix hidden.
mask_token() {
    case "$1" in
        inst_*) printf 'inst_****' ;;
        *) printf '****' ;;
    esac
}

fetch_credentials() {
    INSTALL_TOKEN="$1"

    RESPONSE_FILE=$(mktemp)
    trap "rm -f $RESPONSE_FILE" EXIT

    HTTP_CODE=$(curl -sfL -w "%{http_code}" \
        -o "$RESPONSE_FILE" \
        "${KLYRO_API_URL}/api/v1/agents/install?token=${INSTALL_TOKEN}" \
        -H "User-Agent: klyro-installer/1.0" \
        2>/dev/null) || HTTP_CODE="000"

    case "$HTTP_CODE" in
        200|201)
            log_success "Install token validated"
            ;;
        400)
            log_error "Invalid install token format"
            echo "Please copy the complete token from: https://app.klyro.security/agents/new"
            exit 1
            ;;
        401|403)
            log_error "Install token expired or invalid"
            echo "Generate a new token from: https://app.klyro.security/agents/new"
            exit 1
            ;;
        404)
            log_error "Install token not found"
            exit 1
            ;;
        409)
            log_error "Install token has already been used"
            echo "Generate a new token from: https://app.klyro.security/agents/new"
            exit 1
            ;;
        429)
            log_error "Rate limited - please wait and try again"
            exit 1
            ;;
        000)
            log_error "Cannot connect to Klyro Cloud API"
            echo "Endpoint: ${KLYRO_API_URL}"
            exit 1
            ;;
        *)
            log_error "API error (HTTP $HTTP_CODE)"
            [ "${KLYRO_DEBUG:-}" = "true" ] && cat "$RESPONSE_FILE"
            exit 1
            ;;
    esac

    RESPONSE=$(cat "$RESPONSE_FILE")

    AGENT_ID=$(json_value "$RESPONSE" "agent_id")
    TENANT_ID=$(json_value "$RESPONSE" "tenant_id")
    SITE_ID=$(json_value "$RESPONSE" "site_id")
    CHART_VERSION=$(json_value "$RESPONSE" "chart_version")
    OAUTH2_CLIENT_ID=$(json_value "$RESPONSE" "oauth2_client_id")
    OAUTH2_CLIENT_SECRET=$(json_value "$RESPONSE" "oauth2_client_secret")
    GRPC_ENDPOINT=$(json_value "$RESPONSE" "grpc_endpoint")
    AUTH_ENDPOINT=$(json_value "$RESPONSE" "auth_endpoint")

    GHCR_TOKEN=$(json_value "$RESPONSE" "ghcr_token")

    # Operator keys — server-side default, user env var overrides if set
    local api_anthropic_key=$(json_value "$RESPONSE" "anthropic_api_key")
    if [ -n "$ANTHROPIC_API_KEY" ] && [ -n "$api_anthropic_key" ] && [ "$ANTHROPIC_API_KEY" != "$api_anthropic_key" ]; then
        log_info "Using user-provided ANTHROPIC_API_KEY (overrides default)"
    fi
    ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY:-$api_anthropic_key}"
    OPENAI_API_KEY="${OPENAI_API_KEY:-$(json_value "$RESPONSE" "openai_api_key")}"

    ACCESS_TOKEN="$OAUTH2_CLIENT_SECRET"
    if [ -z "$AGENT_ID" ] || [ -z "$OAUTH2_CLIENT_ID" ] || [ -z "$OAUTH2_CLIENT_SECRET" ]; then
        log_error "Incomplete response from API - missing required credentials"
        [ "${KLYRO_DEBUG:-}" = "true" ] && echo "Response: $RESPONSE"
        exit 1
    fi

    echo ""
    echo "    ┌─────────────────────────────────────────────────────┐"
    echo "    │  Agent ID:      $AGENT_ID"
    echo "    │  Tenant ID:     $TENANT_ID"
    echo "    │  Site ID:       $SITE_ID"
    echo "    │  Chart Version: $CHART_VERSION"
    echo "    │  Telemetry:     Klyro OTLP"
    echo "    └─────────────────────────────────────────────────────┘"
}

# =============================================================================
# Cleanup Existing Installation
# =============================================================================

cleanup_existing_installation() {
    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        kubectl delete helmchart "$RELEASE_NAME" -n kube-system --ignore-not-found >/dev/null 2>&1 || true
    elif command -v helm >/dev/null 2>&1 && helm status "$RELEASE_NAME" -n "$NAMESPACE" >/dev/null 2>&1; then
        log_warn "Found existing Helm release: $RELEASE_NAME"

        helm uninstall "$RELEASE_NAME" -n "$NAMESPACE" --wait >/dev/null 2>&1 &
        UNINSTALL_PID=$!

        UNINSTALL_STATUS=0
        spin_wait "$UNINSTALL_PID" "Uninstalling existing release..." || UNINSTALL_STATUS=$?

        if [ $UNINSTALL_STATUS -eq 0 ]; then
            printf "\r    ${GREEN}[OK]${NC} Existing Helm release uninstalled    \n"
        else
            printf "\r    ${RED}[FAIL]${NC} Failed to uninstall existing release\n"
            exit 1
        fi
    else
        printf "    ${GREEN}[OK]${NC} No existing Helm release found\n"
    fi

    if kubectl get namespace "$NAMESPACE" >/dev/null 2>&1; then
        log_info "Cleaning up namespace resources..."

        kubectl delete secret klyro-cloud-credentials -n "$NAMESPACE" --ignore-not-found >/dev/null 2>&1
        kubectl delete secret klyro-registry-secret -n "$NAMESPACE" --ignore-not-found >/dev/null 2>&1
        kubectl delete secret klyro-edge-oauth-credentials -n "$NAMESPACE" --ignore-not-found >/dev/null 2>&1
        kubectl delete secret anthropic-credentials -n "$NAMESPACE" --ignore-not-found >/dev/null 2>&1
        kubectl delete secret datadog-secrets -n "$NAMESPACE" --ignore-not-found >/dev/null 2>&1
        printf "    ${GREEN}[OK]${NC} Secrets cleaned up\n"

        kubectl delete pods -n "$NAMESPACE" --all --ignore-not-found >/dev/null 2>&1

        kubectl wait --for=delete pod --all -n "$NAMESPACE" --timeout=60s >/dev/null 2>&1 &
        WAIT_PID=$!

        spin_wait "$WAIT_PID" "Waiting for pods to terminate..." || true
        printf "\r    ${GREEN}[OK]${NC} Pods terminated                  \n"
    else
        printf "    ${GREEN}[OK]${NC} No existing namespace found\n"
    fi
}

# =============================================================================
# Kubernetes Resources Creation
# =============================================================================

EXTRA_CA_CONFIGMAP="klyro-extra-ca"

# True when the releases should mount the extra CA ConfigMap: --ca-file on this
# run, or a --reinstall whose original install used one (EXTRA_CA_RECOVERED).
extra_ca_enabled() {
    [ -n "${CA_FILE:-}" ] || [ "${EXTRA_CA_RECOVERED:-}" = "true" ]
}

# Checks the egress settings, from flags or recovered by --reinstall.
validate_egress_settings() {
    case "$PROXY_URL" in
        ""|http://*) ;;
        *)
            log_error "The proxy must be an http:// URL (grpc-go cannot reach an https:// proxy)"
            exit 1
            ;;
    esac
    case "$CHART_REPO" in
        ""|oci://*) ;;
        *)
            log_error "--chart-repo must be an oci:// URL"
            exit 1
            ;;
    esac
    # Saved into klyro-agent-info as JSON on --reinstall: no quotes or backslashes.
    case "$NO_PROXY_EXTRA$CHART_REPO" in
        *[\"\\]*)
            log_error "--no-proxy and --chart-repo cannot contain quotes or backslashes"
            exit 1
            ;;
    esac
}

# The entries of this shell's NO_PROXY and no_proxy, comma-separated, without those the
# chart always sets, duplicates, blanks, quotes and backslashes.
env_no_proxy_extra() {
    printf '%s\n' "${NO_PROXY:-},${no_proxy:-}" | tr ',' '\n' | sed 's/[[:space:]"\\]//g' | awk '
        $0 == "" || seen[$0]++ { next }
        /^(localhost|127\.0\.0\.1|::1|\.svc|\.cluster\.local|kubernetes\.default|10\.42\.0\.0\/16|10\.43\.0\.0\/16)$/ { next }
        { out = out (out == "" ? "" : ",") $0 }
        END { print out }'
}

# Without --proxy, takes this shell's HTTPS proxy (https_proxy before HTTPS_PROXY, as curl
# picks it) as PROXY_URL when it is an http:// URL, and without --no-proxy seeds
# NO_PROXY_EXTRA from env_no_proxy_extra. An https:// proxy is ignored with a warning.
detect_env_proxy() {
    local name=https_proxy env_proxy
    [ -z "$PROXY_URL" ] || return 0
    env_proxy="${https_proxy:-}"
    if [ -z "$env_proxy" ]; then
        name=HTTPS_PROXY env_proxy="${HTTPS_PROXY:-}"
    fi
    [ -n "$env_proxy" ] || return 0
    case "$env_proxy" in
        http://*) ;;
        *)
            log_warn "$name $(pf_redact_url "$env_proxy") is not an http:// URL, so k3s and the pods do not use it (grpc-go cannot reach an https:// proxy): pass --proxy http://<host>:<port>"
            return 0
            ;;
    esac
    PROXY_URL="$env_proxy" PROXY_AUTO=true
    log_info "proxy auto-detected from $name: $(pf_redact_url "$PROXY_URL") for k3s and the pods (--proxy overrides it)"
    if [ -z "$NO_PROXY_EXTRA" ]; then
        NO_PROXY_EXTRA=$(env_no_proxy_extra)
        [ -z "$NO_PROXY_EXTRA" ] || log_info "NO_PROXY for the pods from the shell's NO_PROXY: $NO_PROXY_EXTRA (--no-proxy overrides it)"
    fi
}

resolve_egress() {
    local api_ip
    if [ -n "$CA_FILE" ]; then
        if [ ! -r "$CA_FILE" ] || ! grep -q -- '-----BEGIN CERTIFICATE-----' "$CA_FILE"; then
            log_error "--ca-file $CA_FILE is not a readable PEM certificate bundle"
            exit 1
        fi
    fi
    [ -n "$PROXY_URL" ] || return 0
    api_ip=$(kubectl get service kubernetes --namespace default -o jsonpath='{.spec.clusterIP}' 2>/dev/null || true)
    NO_PROXY_VALUE="${NO_PROXY_EXTRA}"
    if [ -n "$api_ip" ]; then
        NO_PROXY_VALUE="${NO_PROXY_VALUE:+$NO_PROXY_VALUE,}${api_ip}"
    fi
    log_info "Pods egress through the proxy; in-cluster names, k3s CIDRs and ${NO_PROXY_VALUE:-nothing else} bypass it"
}

create_extra_ca_configmap() {
    local ns
    [ -n "$CA_FILE" ] || return 0
    for ns in "$NAMESPACE" ${1:-}; do
        kubectl create configmap "$EXTRA_CA_CONFIGMAP" --from-file=ca.crt="$CA_FILE" \
            --namespace="$ns" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
    done
    printf "    ${GREEN}[OK]${NC} ConfigMap: ${EXTRA_CA_CONFIGMAP} (extra CA bundle)\n"
}

# The --proxy URL may carry credentials, so it is kept only in this Secret.
EGRESS_PROXY_SECRET="klyro-egress-proxy"

create_egress_proxy_secret() {
    local f
    [ -n "$PROXY_URL" ] || return 0
    f=$(mktemp)
    chmod 600 "$f"
    printf '%s' "$PROXY_URL" > "$f"
    kubectl create secret generic "$EGRESS_PROXY_SECRET" --from-file=proxy-url="$f" \
        --namespace="$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
    rm -f "$f"
    printf "    %b[OK]%b Secret: %s (proxy URL)\n" "$GREEN" "$NC" "$EGRESS_PROXY_SECRET"
}

egress_values() {
    if [ -n "${PROXY_URL:-}" ]; then
        echo "proxy:"
        echo "  existingSecret: ${EGRESS_PROXY_SECRET}"
        echo "  existingSecretKey: proxy-url"
        [ -n "${NO_PROXY_VALUE:-}" ] && echo "  noProxy: \"${NO_PROXY_VALUE}\""
    fi
    if extra_ca_enabled; then
        echo "extraCA:"
        echo "  existingConfigMap: ${EXTRA_CA_CONFIGMAP}"
    fi
    return 0
}

create_namespace() {
    kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
    printf "    ${GREEN}[OK]${NC} Namespace: $NAMESPACE\n"
}

create_registry_secret() {
    if [ -z "$GHCR_TOKEN" ]; then
        log_warn "No GHCR token provided - skipping registry secret"
        printf "    ${YELLOW}[SKIP]${NC} Registry secret (no ghcr_token in API response)\n"
        return 0
    fi

    kubectl create secret docker-registry klyro-registry-secret \
        --docker-server="ghcr.io" \
        --docker-username="klyrohq" \
        --docker-password="$GHCR_TOKEN" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null

    printf "    ${GREEN}[OK]${NC} Secret: klyro-registry-secret (GHCR)\n"

    kubectl create secret generic ghcr-credentials \
        --from-literal=username="klyrohq" \
        --from-literal=token="$GHCR_TOKEN" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null

    printf "    ${GREEN}[OK]${NC} Secret: ghcr-credentials (OTA chart pulls)\n"
}


create_cloud_credentials_secret() {
    kubectl create secret generic klyro-cloud-credentials \
        --from-literal=agent-id="$AGENT_ID" \
        --from-literal=access-token="$ACCESS_TOKEN" \
        --from-literal=install-token="$INSTALL_TOKEN" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null

    printf "    ${GREEN}[OK]${NC} Secret: klyro-cloud-credentials\n"
}

create_oauth_credentials_secret() {
    kubectl create secret generic klyro-edge-oauth-credentials \
        --from-literal=client-id="$OAUTH2_CLIENT_ID" \
        --from-literal=client-secret="$OAUTH2_CLIENT_SECRET" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null

    printf "    ${GREEN}[OK]${NC} Secret: klyro-edge-oauth-credentials\n"
}

create_anthropic_secret() {
    # LLM egress gateway is the default LLM path (non-local): the operator calls
    # llm.<env>.klyro.security, which holds the real Anthropic key server-side and
    # authorizes the agent by its Keycloak token. So no raw key is required at the
    # customer. The chart still mounts ANTHROPIC_API_KEY, so create the secret with
    # a placeholder when no real key is provided (it is unused in gateway mode).
    local key_value="$ANTHROPIC_API_KEY"
    if [ -z "$key_value" ]; then
        if [ "$is_local" = "true" ]; then
            log_error "ANTHROPIC_API_KEY required for --local (no LLM gateway). Provide: ANTHROPIC_API_KEY=sk-ant-... ./install.sh ..."
            exit 1
        fi
        key_value="unused-gateway"
        log_info "No Anthropic key: operator will use the llm.${KLYRO_ENV:-prod}.klyro.security egress gateway"
    fi

    kubectl create secret generic anthropic-credentials \
        --from-literal=api-key="$key_value" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null

    printf "    ${GREEN}[OK]${NC} Secret: anthropic-credentials\n"
}

create_openai_secret() {
    if [ -n "$OPENAI_API_KEY" ]; then
        kubectl create secret generic openai-credentials \
            --from-literal=api-key="$OPENAI_API_KEY" \
            --namespace="$NAMESPACE" \
            --dry-run=client -o yaml | kubectl apply -f - >/dev/null
        printf "    ${GREEN}[OK]${NC} Secret: openai-credentials\n"
    else
        kubectl create secret generic openai-credentials \
            --from-literal=api-key="not-configured" \
            --namespace="$NAMESPACE" \
            --dry-run=client -o yaml | kubectl apply -f - >/dev/null
        printf "    ${YELLOW}[INFO]${NC} Secret: openai-credentials (placeholder)\n"
    fi
}

# =============================================================================
# Helm Installation
# =============================================================================

# The values below mirror the --set flags that install_helm_chart() builds for the
# helm-binary path — the two must be kept in sync.
install_via_helm_controller() {
    local image_tag="$1" default_sc="$2" detected_env="$3" otel_ingest_host="$4"
    local otel_token_url="$5"
    local vals
    vals=$(mktemp)

    {
        echo "global:"
        echo "  imagePullSecrets: null"
        echo "agent:"
        echo "  image:"
        echo "    repository: $(install_image_repository klyro-edge agent.image)"
        echo "    pullPolicy: Always"
        [ -n "$image_tag" ] && echo "    tag: \"${image_tag}\""
        echo "  persistence:"
        echo "    enabled: true"
        [ -n "$default_sc" ] && echo "    storageClass: ${default_sc}"
        if [ -n "$CHART_REPO" ]; then
            echo "  helm:"
            echo "    chartRepo: \"${CHART_REPO}\""
        fi
        echo "worker:"
        echo "  enabled: true"
        echo "  mode: edge"
        echo "  environment: ${detected_env}"
        echo "  image:"
        echo "    repository: $(install_image_repository klyro-edge worker.image)"
        echo "    pullPolicy: Always"
        [ -n "$image_tag" ] && echo "    tag: \"${image_tag}\""
        echo "  anthropic:"
        echo "    baseUrl: ${LLM_GATEWAY_URL}"
        echo "    secretName: anthropic-credentials"
        echo "    secretKey: api-key"
        echo "    gatewayAuth:"
        echo "      enabled: true"
        echo "      tokenUrl: ${AUTH_ENDPOINT%/}"
        echo "  temporal:"
        echo "    hostPort: temporal-frontend:7233"
        echo "    namespace: default"
        echo "    taskQueue: klyro-tasks"
        echo "klyroCloud:"
        echo "  grpc:"
        echo "    endpoint: ${GRPC_ENDPOINT}"
        echo "  apiKeySecretName: klyro-cloud-credentials"
        echo "  apiKeySecretKey: access-token"
        echo "  agentIdSecretKey: agent-id"
        echo "  heartbeat:"
        echo "    enabled: true"
        echo "    intervalSeconds: 30"
        echo "  gatewayHttpUrl: ${KLYRO_API_URL}"
        echo "opentelemetry:"
        echo "  enabled: true"
        echo "  environment: ${detected_env}"
        echo "  clusterName: ${AGENT_ID}"
        echo "  tenantId: ${TENANT_ID}"
        echo "  siteId: ${SITE_ID}"
        echo "  collector:"
        echo "    enabled: true"
        echo "    image:"
        echo "      repository: $(install_image_repository klyro-edge opentelemetry.collector.image)"
        echo "    exporters:"
        echo "      prometheus:"
        echo "        enabled: true"
        echo "      remoteOtlp:"
        echo "        enabled: true"
        echo "        endpoint: https://${otel_ingest_host}"
        if [ -n "$AUTH_ENDPOINT" ]; then
            echo "        auth:"
            echo "          tokenUrl: ${otel_token_url}"
        fi
        if [ -n "$DATADOG_API_KEY" ]; then
            echo "      datadog:"
            echo "        enabled: true"
        fi
        echo "ecr:"
        echo "  enabled: false"
        echo "imagePullSecrets:"
        echo "  create: false"
        echo "temporal:"
        echo "  enabled: false"
        egress_values
    } > "$vals"

    apply_helm_controller_chart "$RELEASE_NAME" "$CHART_PATH" "$CHART_VERSION" "$vals"
    rm -f "$vals"
}

# Installs a chart through a HelmChart CR in kube-system and waits for k3s's Helm
# controller to finish the helm-install-<release> Job.
apply_helm_controller_chart() {
    local release="$1" chart="$2" version="$3" vals="$4" failure_policy="${5:-}"
    local crd old_job job_uid out err
    crd=$(mktemp)
    err=$(mktemp)
    # An existing HelmChart (an MC re-run upgrades it in place) still has the completed Job of
    # its last install: wait for the one the new spec starts, not that one.
    if ! old_job=$(kubectl get job "helm-install-${release}" -n kube-system --ignore-not-found \
        -o jsonpath='{.metadata.uid}' 2>"$err"); then
        log_error "Cannot read the Helm controller's install Job helm-install-${release}"
        sed 's/^/    /' "$err" >&2
        rm -f "$err" "$crd"
        exit 1
    fi
    rm -f "$err"

    {
        echo "apiVersion: helm.cattle.io/v1"
        echo "kind: HelmChart"
        echo "metadata:"
        echo "  name: ${release}"
        echo "  namespace: kube-system"
        echo "spec:"
        echo "  chart: ${chart}"
        [ -n "$version" ] && echo "  version: ${version}"
        echo "  targetNamespace: ${NAMESPACE}"
        echo "  createNamespace: false"
        [ -z "$failure_policy" ] || echo "  failurePolicy: ${failure_policy}"
        if extra_ca_enabled; then
            echo "  repoCAConfigMap:"
            echo "    name: ${EXTRA_CA_CONFIGMAP}"
        fi
        echo "  valuesContent: |-"
        sed 's/^/    /' "$vals"
    } > "$crd"

    log_info "Installing chart via k3s Helm controller (HelmChart/${release})..."
    if ! out=$(kubectl apply -f "$crd" 2>&1); then
        log_error "Failed to apply HelmChart resource"
        printf '%s\n' "$out" >&2
        cat "$crd"
        exit 1
    fi
    case "$out" in
        *" unchanged"*) old_job="" ;;
    esac

    # helm-controller reconciles the HelmChart into a Job named helm-install-<name>.
    log_info "Waiting for the Helm controller to install the chart (up to 15m)..."
    local t=0
    while :; do
        job_uid=$(kubectl get job "helm-install-${release}" -n kube-system -o jsonpath='{.metadata.uid}' 2>/dev/null || true)
        [ -n "$job_uid" ] && [ "$job_uid" != "$old_job" ] && break
        t=$((t + 1))
        [ "$t" -gt 90 ] && { log_error "Helm controller did not create an install job"; exit 1; }
        sleep 2
    done
    if ! kubectl wait --for=condition=complete "job/helm-install-${release}" -n kube-system --timeout=900s >/dev/null 2>&1; then
        log_error "Helm controller install did not complete"
        kubectl logs -n kube-system "job/helm-install-${release}" --tail=60 2>/dev/null || true
        exit 1
    fi

    rm -f "$crd"
    log_success "Helm chart installed successfully (via k3s Helm controller)"
}

fetch_oci_chart() {
    local dest="$1"
    local chart="${2:-$CHART_PATH}"
    local version="${3-$CHART_VERSION}"
    local attempt=1
    local max_attempts=3
    local delay=5
    local out=""
    while :; do
        if out=$(helm pull "$chart" ${version:+--version "$version"} --destination "$dest" 2>&1); then
            return 0
        fi
        case "$out" in
            *"status code 401"*|*"status code 403"*|*"status code 404"*|*nauthorized*|*denied*|*"not found"*)
                attempt=$max_attempts
                ;;
        esac
        if [ "$attempt" -ge "$max_attempts" ]; then
            log_error "Chart fetch failed: ${chart}${version:+ $version}"
            printf "%s\n" "$out" >&2
            return 1
        fi
        log_warn "Chart fetch failed: $(printf '%s\n' "$out" | tail -1)"
        log_warn "Retrying chart fetch ($((attempt + 1))/${max_attempts}) in ${delay}s..."
        sleep "$delay"
        attempt=$((attempt + 1))
        delay=$((delay * 2))
    done
}

install_helm_chart() {
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
    LOCAL_CHART_PATH="${SCRIPT_DIR}/../charts/klyro-edge"
    OCI_CHART="oci://${KLYRO_REGISTRY}/klyrohq/klyro-security/charts/klyro-edge"

    if [ -d "$LOCAL_CHART_PATH" ]; then
        CHART_PATH="$LOCAL_CHART_PATH"
        log_info "Using local chart: $CHART_PATH"
    else
        CHART_PATH="$OCI_CHART"
        log_info "Local chart not found, using OCI registry: $CHART_PATH"

        # Chart is served anonymously via the registry.<env>.klyro.security
        # pull-through cache (zot -> ghcr) — no ghcr login required.

        if [ -n "$CHART_VERSION" ]; then
            log_info "Chart version: $CHART_VERSION"
        fi
    fi

    HELM_ARGS="--namespace $NAMESPACE"

    # Determine image tag — use chart version SHA if available, fallback to latest
    local IMAGE_TAG="latest"
    if [ -n "$CHART_VERSION" ]; then
        case "$CHART_VERSION" in
            *.*)
                # Chart version is set — the chart's values.yaml already has the correct SHA-pinned image tags
                # Don't override image tags; let the chart defaults handle it
                IMAGE_TAG=""
                ;;
        esac
    fi

    if [ "$is_local" != "true" ]; then
        # Customer/cloud install: all images pulled anonymously via the
        # registry.<env>.klyro.security pull-through cache (zot -> ghcr/docker.io).
        # No ghcr token needed (pull-through is anonymous), so this path is gated
        # on "not --local", not on GHCR_TOKEN.
        HELM_ARGS="$HELM_ARGS --set global.imagePullSecrets=null"
        HELM_ARGS="$HELM_ARGS --set agent.image.repository=$(install_image_repository klyro-edge agent.image)"
        HELM_ARGS="$HELM_ARGS --set worker.image.repository=$(install_image_repository klyro-edge worker.image)"
        HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.image.repository=$(install_image_repository klyro-edge opentelemetry.collector.image)"
        if [ -n "$IMAGE_TAG" ]; then
            HELM_ARGS="$HELM_ARGS --set agent.image.tag=${IMAGE_TAG}"
            HELM_ARGS="$HELM_ARGS --set worker.image.tag=${IMAGE_TAG}"
        fi
        # Route the operator's LLM through the llm.<env>.klyro.security egress gateway
        # (no raw Anthropic key at the customer; gateway holds it server-side and
        # authorizes by the agent's Keycloak token). Creds reuse klyro-edge-oauth-credentials.
        # AUTH_ENDPOINT is the gateway-http token proxy (…/api/v1/auth/token) — already the
        # complete token URL, so use it verbatim (do NOT append the Keycloak /protocol/… path).
        HELM_ARGS="$HELM_ARGS --set worker.anthropic.baseUrl=${LLM_GATEWAY_URL}"
        HELM_ARGS="$HELM_ARGS --set worker.anthropic.gatewayAuth.enabled=true"
        HELM_ARGS="$HELM_ARGS --set worker.anthropic.gatewayAuth.tokenUrl=${AUTH_ENDPOINT%/}"
        log_info "Using registry pull-through: ${KLYRO_REGISTRY}; LLM via ${LLM_GATEWAY_URL}"
    else
        HELM_ARGS="$HELM_ARGS --set global.imagePullSecrets=null"
        HELM_ARGS="$HELM_ARGS --set agent.image.repository=${K3D_REGISTRY}/klyro-agent"
        HELM_ARGS="$HELM_ARGS --set agent.image.tag=dev"
        HELM_ARGS="$HELM_ARGS --set worker.image.repository=${K3D_REGISTRY}/klyro-operator"
        HELM_ARGS="$HELM_ARGS --set worker.image.tag=dev"
        log_info "Local mode: using k3d registry ${K3D_REGISTRY}"
    fi

    HELM_ARGS="$HELM_ARGS --set agent.image.pullPolicy=Always"
    HELM_ARGS="$HELM_ARGS --set agent.persistence.enabled=true"

    local DEFAULT_SC=$(kubectl get storageclass -o jsonpath='{.items[?(@.metadata.annotations.storageclass\.kubernetes\.io/is-default-class=="true")].metadata.name}' 2>/dev/null)
    if [ -z "$DEFAULT_SC" ]; then
        DEFAULT_SC=$(kubectl get storageclass -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)
    fi
    if [ -n "$DEFAULT_SC" ]; then
        HELM_ARGS="$HELM_ARGS --set agent.persistence.storageClass=$DEFAULT_SC"
        log_info "Using storage class: $DEFAULT_SC"
    fi

    HELM_ARGS="$HELM_ARGS --set klyroCloud.grpc.endpoint=$GRPC_ENDPOINT"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.apiKeySecretName=klyro-cloud-credentials"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.apiKeySecretKey=access-token"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.agentIdSecretKey=agent-id"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.heartbeat.enabled=true"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.heartbeat.intervalSeconds=30"
    HELM_ARGS="$HELM_ARGS --set klyroCloud.gatewayHttpUrl=${KLYRO_API_URL}"

    HELM_ARGS="$HELM_ARGS --set worker.enabled=true"
    HELM_ARGS="$HELM_ARGS --set worker.image.pullPolicy=Always"
    HELM_ARGS="$HELM_ARGS --set worker.mode=edge"
    # Detect environment from gRPC endpoint (telemetry env tag)
    local detected_env="production"
    case "$GRPC_ENDPOINT" in
        *dev.*)
            detected_env="dev"
            ;;
        *staging.*)
            detected_env="staging"
            ;;
    esac
    HELM_ARGS="$HELM_ARGS --set worker.environment=${detected_env}"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.environment=${detected_env}"
    HELM_ARGS="$HELM_ARGS --set worker.anthropic.secretName=anthropic-credentials"
    HELM_ARGS="$HELM_ARGS --set worker.anthropic.secretKey=api-key"
    HELM_ARGS="$HELM_ARGS --set temporal.enabled=false"
    HELM_ARGS="$HELM_ARGS --set worker.temporal.hostPort=temporal-frontend:7233"
    HELM_ARGS="$HELM_ARGS --set worker.temporal.namespace=default"
    HELM_ARGS="$HELM_ARGS --set worker.temporal.taskQueue=klyro-tasks"

    HELM_ARGS="$HELM_ARGS --set opentelemetry.enabled=true"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.enabled=true"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.clusterName=$AGENT_ID"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.tenantId=$TENANT_ID"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.siteId=$SITE_ID"
    HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.exporters.prometheus.enabled=true"

    # Remote OTLP export to Klyro central observability (always enabled)
    # Derive telemetry ingest endpoint from gRPC endpoint environment
    local otel_ingest_host
    otel_ingest_host=$(otel_ingest_host_for_env "$GRPC_ENDPOINT")
    HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.exporters.remoteOtlp.enabled=true"
    # OTLP/HTTP over 443 (https URL, no :4320). CloudFront terminates TLS at
    # otel-ingest.<env> and the otlphttp exporter appends /v1/{logs,traces,metrics}.
    HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.exporters.remoteOtlp.endpoint=https://${otel_ingest_host}"
    if [ -n "$AUTH_ENDPOINT" ]; then
        case "${AUTH_ENDPOINT%/}" in
            */protocol/openid-connect/token) otel_token_url="${AUTH_ENDPOINT%/}" ;;
            */realms/*) otel_token_url="${AUTH_ENDPOINT%/}/protocol/openid-connect/token" ;;
            *)          otel_token_url="${AUTH_ENDPOINT%/}" ;;
        esac
        HELM_ARGS="$HELM_ARGS --set opentelemetry.collector.exporters.remoteOtlp.auth.tokenUrl=${otel_token_url}"
    fi


    HELM_ARGS="$HELM_ARGS --set ecr.enabled=false"
    HELM_ARGS="$HELM_ARGS --set imagePullSecrets.create=false"
    if [ -n "$CHART_REPO" ]; then
        HELM_ARGS="$HELM_ARGS --set agent.helm.chartRepo=${CHART_REPO}"
    fi

    HELM_ARGS="$HELM_ARGS --wait --timeout 15m"

    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        install_via_helm_controller "$IMAGE_TAG" "$DEFAULT_SC" "$detected_env" "$otel_ingest_host" "$otel_token_url"
        return
    fi

    HELM_OUTPUT=$(mktemp)
    CHART_PULL_DIR=$(mktemp -d)
    trap "rm -rf $HELM_OUTPUT $CHART_PULL_DIR" EXIT
    egress_values > "$CHART_PULL_DIR/egress-values.yaml"
    if [ -s "$CHART_PULL_DIR/egress-values.yaml" ]; then
        HELM_ARGS="$HELM_ARGS -f $CHART_PULL_DIR/egress-values.yaml"
    fi
    case "$CHART_PATH" in
        oci://*)
            log_info "Fetching chart from OCI registry..."
            fetch_oci_chart "$CHART_PULL_DIR" || exit 1
            CHART_PATH=$(find "$CHART_PULL_DIR" -name '*.tgz' | head -1)
            log_success "Chart fetched: $(basename "$CHART_PATH")"
            ;;
    esac

    log_info "Running Helm upgrade/install (this may take a few minutes)..."
    echo ""

    if [ "${KLYRO_DEBUG:-}" = "true" ]; then
        # ${PIPESTATUS[0]} is a bash array expansion (dash: "Bad substitution").
        # Capture helm's own exit status via a temp file instead, so the output is
        # still streamed live through tee. The && / || list keeps `set -e` from
        # killing the pipeline subshell before the status is recorded.
        HELM_RC_FILE=$(mktemp)
        # Re-arm the EXIT trap to cover both temp files, so an interrupt mid-helm
        # (Ctrl-C) does not leak the rc file.
        trap "rm -rf $HELM_OUTPUT $HELM_RC_FILE $CHART_PULL_DIR" EXIT
        { helm upgrade --install "$RELEASE_NAME" "$CHART_PATH" $HELM_ARGS 2>&1 \
            && echo 0 >"$HELM_RC_FILE" || echo $? >"$HELM_RC_FILE"; } | tee "$HELM_OUTPUT"
        HELM_STATUS=$(cat "$HELM_RC_FILE" 2>/dev/null || echo 1)
        rm -f "$HELM_RC_FILE"
    else
        helm upgrade --install "$RELEASE_NAME" "$CHART_PATH" $HELM_ARGS >"$HELM_OUTPUT" 2>&1 &
        HELM_PID=$!

        # Show progress while helm runs
        HELM_STATUS=0
        spin_wait "$HELM_PID" "Deploying Klyro Edge..." || HELM_STATUS=$?

        if [ $HELM_STATUS -eq 0 ]; then
            printf "\r    ${GREEN}[OK]${NC} Deploying Klyro Edge      \n"
        else
            printf "\r    ${RED}[FAIL]${NC} Deploying Klyro Edge      \n"
        fi
    fi

    if [ "$HELM_STATUS" -ne 0 ]; then
        # $HELM_OUTPUT captures helm's stdout AND stderr (">$HELM_OUTPUT 2>&1" above,
        # "2>&1 | tee" in the debug branch), so the real error message lands here
        # whichever stream helm wrote it to.
        log_error "Helm installation failed (exit $HELM_STATUS)"
        echo ""
        echo "Helm output:"
        cat "$HELM_OUTPUT"
        echo ""
        echo "Debug commands:"
        echo "  kubectl get pods -n $NAMESPACE"
        echo "  kubectl describe pods -n $NAMESPACE"
        echo "  kubectl logs -n $NAMESPACE -l app.kubernetes.io/name=klyro-agent"
        exit "$HELM_STATUS"
    fi

    log_success "Helm chart installed successfully"
}

# =============================================================================
# Verification
# =============================================================================

# Prints "<newest Helm revision>:<Deployment generation>"; a field it cannot read is empty.
rollout_state() {
    local release="$1" deploy="$2" rev gen
    rev=$(kubectl get secrets -n "$NAMESPACE" -l "owner=helm,name=${release}" --request-timeout=10s \
        -o jsonpath='{range .items[*]}{.metadata.labels.version}{"\n"}{end}' 2>/dev/null | sort -n | tail -1)
    gen=$(kubectl get deployment "$deploy" -n "$NAMESPACE" --request-timeout=10s \
        -o jsonpath='{.metadata.generation}' 2>/dev/null) || gen=""
    echo "${rev}:${gen}"
}

# True when a field read in both rollout_state values changed.
rollout_state_changed() {
    local b_rev="${1%%:*}" b_gen="${1#*:}" a_rev="${2%%:*}" a_gen="${2#*:}"
    { [ -n "$b_rev" ] && [ -n "$a_rev" ] && [ "$a_rev" != "$b_rev" ]; } ||
        { [ -n "$b_gen" ] && [ -n "$a_gen" ] && [ "$a_gen" != "$b_gen" ]; }
}

# Records the agent and worker rollout_state right after the installer applied the chart.
record_rollout_baselines() {
    AGENT_ROLLOUT_BASE=$(rollout_state "$RELEASE_NAME" "${RELEASE_NAME}-agent")
    WORKER_ROLLOUT_BASE=$(rollout_state "$RELEASE_NAME" "${RELEASE_NAME}-worker")
}

# Waits up to <timeout>s for a Deployment's rollout. When it fails after the release got a
# new Helm revision or the Deployment a new generation since <before> (default: now), an
# agent self-upgrade during the install, follows the new rollout for up to
# SELF_UPGRADE_TIMEOUT more, after up to 60s for a new revision to reach the Deployment.
# Sets ROLLOUT_WAITED.
wait_rollout() {
    local release="$1" deploy="$2" timeout="$3" msg="$4" before="${5:-}" after try rc=0
    ROLLOUT_WAITED=$timeout
    [ -n "$before" ] || before=$(rollout_state "$release" "$deploy")
    kubectl rollout status "deployment/${deploy}" -n "$NAMESPACE" --timeout="${timeout}s" >/dev/null 2>&1 &
    spin_wait "$!" "$msg" || rc=$?
    [ "$rc" -ne 0 ] || return 0
    for try in 1 2 3; do
        after=$(rollout_state "$release" "$deploy")
        rollout_state_changed "$before" "$after" && break
        case "$after" in :*|*:) [ "$try" -lt 3 ] && sleep 5 ;; *) return "$rc" ;; esac
    done
    rollout_state_changed "$before" "$after" || return "$rc"

    ROLLOUT_WAITED=$((timeout + SELF_UPGRADE_TIMEOUT))
    printf "\r    ${YELLOW}[...]${NC} %s was upgraded during the install; following the new rollout (up to %ss more)\n" \
        "$deploy" "$SELF_UPGRADE_TIMEOUT"
    try=0
    while [ -n "${before#*:}" ] && [ "${after#*:}" = "${before#*:}" ] && [ "$try" -lt 12 ]; do
        sleep 5
        try=$((try + 1))
        after=$(rollout_state "$release" "$deploy")
    done
    rc=0
    kubectl rollout status "deployment/${deploy}" -n "$NAMESPACE" --timeout="${SELF_UPGRADE_TIMEOUT}s" >/dev/null 2>&1 &
    spin_wait "$!" "$msg" || rc=$?
    return "$rc"
}

verify_installation() {
    local chart
    echo ""
    [ -n "${WORKER_ROLLOUT_BASE:-}" ] || WORKER_ROLLOUT_BASE=$(rollout_state "$RELEASE_NAME" "${RELEASE_NAME}-worker")

    # --- Agent deployment rollout (blocking) ---
    # NB: $spinstr is still used by the health-check retry loop further down.
    local spinstr='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
    ROLLOUT_STATUS=0
    wait_rollout "$RELEASE_NAME" "${RELEASE_NAME}-agent" 120 "Waiting for agent deployment..." "${AGENT_ROLLOUT_BASE:-}" || ROLLOUT_STATUS=$?

    if [ $ROLLOUT_STATUS -eq 0 ]; then
        printf "\r    ${GREEN}[OK]${NC} Agent deployment ready        \n"
        chart=$(kubectl get deployment "${RELEASE_NAME}-agent" -n "$NAMESPACE" --request-timeout=10s \
            -o jsonpath='{.metadata.labels.helm\.sh/chart}' 2>/dev/null) || chart=""
        chart=${chart#klyro-edge-}
        if [ -z "$chart" ]; then
            :
        elif [ -n "$CHART_VERSION" ] && [ "$CHART_VERSION" != "local" ] && [ "$chart" != "$CHART_VERSION" ]; then
            log_info "The agent upgraded itself to chart ${chart} during install (installed ${CHART_VERSION})"
        elif [ -z "$CHART_VERSION" ]; then
            log_info "Agent chart: ${chart}"
        fi
    else
        printf "\r    ${RED}[FAIL]${NC} Agent deployment did not become ready (watch budget %ss)\n" "$ROLLOUT_WAITED"
        log_error "Agent pod failed to start. Debug with:"
        echo "  kubectl get pods -n $NAMESPACE"
        echo "  kubectl describe pod -n $NAMESPACE -l app.kubernetes.io/instance=${RELEASE_NAME},app.kubernetes.io/component=agent"
        echo "  kubectl logs -n $NAMESPACE -l app.kubernetes.io/instance=${RELEASE_NAME},app.kubernetes.io/component=agent"
        exit 1
    fi

    # --- Health check with retry (blocking, up to 60s) ---
    local max_retries=12
    local retry_interval=5
    local health_ok=false
    local probe_broken=""
    local probe_err
    probe_err=$(mktemp)

    for attempt in $(seq 1 $max_retries); do
        POD_NAME=$(kubectl get pods -n "$NAMESPACE" \
            -l app.kubernetes.io/instance=${RELEASE_NAME},app.kubernetes.io/component=agent \
            -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)

        if [ -z "$POD_NAME" ]; then
            printf "\r    ${BLUE}[%s]${NC} Waiting for agent pod... (attempt %d/%d)" \
                "$(echo $spinstr | cut -c$(( (attempt % 10) + 1 )))" "$attempt" "$max_retries"
            sleep $retry_interval
            continue
        fi

        # curl, not wget: the agent runtime image is debian:bookworm-slim plus
        # ca-certificates/tzdata/bash/curl/openssl — it has no wget at all. The old
        # `wget -qO-` probe could therefore never run; its "command not found" went to
        # /dev/null, $HEALTH stayed empty, all 12 attempts "failed", and the installer
        # exited 1 with "Agent is running but not healthy" on a perfectly healthy
        # agent. That made every install fail its final step (KAN-696).
        HEALTH=""
        PROBE_RC=0
        HEALTH=$(kubectl exec -n "$NAMESPACE" "$POD_NAME" -- \
            curl -sf http://localhost:8080/health 2>"$probe_err") || PROBE_RC=$?

        if printf '%s\n' "$HEALTH" | grep -qi "ok"; then
            health_ok=true
            break
        fi

        # "The probe could not run" is a different condition from "the agent is not
        # healthy yet". Conflating them is exactly what hid KAN-696, so bail out and
        # say so instead of retrying 12 times and then blaming the agent.
        if [ "$PROBE_RC" -ne 0 ] && grep -qiE \
            'executable file not found|command not found|no such file or directory|OCI runtime exec failed|error executing command' \
            "$probe_err"; then
            probe_broken=$(cat "$probe_err")
            break
        fi

        printf "\r    ${BLUE}[%s]${NC} Health check... (attempt %d/%d)        " \
            "$(echo $spinstr | cut -c$(( (attempt % 10) + 1 )))" "$attempt" "$max_retries"
        sleep $retry_interval
    done
    rm -f "$probe_err"

    if [ "$health_ok" = "true" ]; then
        printf "\r    ${GREEN}[OK]${NC} Health check passed                    \n"
    elif [ -n "$probe_broken" ]; then
        printf "\r    ${RED}[FAIL]${NC} Health probe could not run inside the agent container\n"
        log_error "The health probe itself failed to execute - this is an installer/image problem, not necessarily an unhealthy agent."
        echo "  Probe error: $probe_broken"
        echo ""
        echo "The agent may well be running correctly. Check it directly:"
        echo "  kubectl get pod -n $NAMESPACE $POD_NAME"
        echo "  kubectl logs -n $NAMESPACE $POD_NAME"
        echo "  kubectl exec -n $NAMESPACE $POD_NAME -- curl -sf http://localhost:8080/health"
        exit 1
    else
        printf "\r    ${RED}[FAIL]${NC} Health check failed after ${max_retries} attempts\n"
        log_error "Agent is running but not healthy. Debug with:"
        echo "  kubectl logs -n $NAMESPACE $POD_NAME"
        exit 1
    fi

    # --- Worker/operator deployment check ---
    WORKER_STATUS=0
    wait_rollout "$RELEASE_NAME" "${RELEASE_NAME}-worker" 120 "Waiting for worker deployment..." "$WORKER_ROLLOUT_BASE" || WORKER_STATUS=$?

    if [ $WORKER_STATUS -eq 0 ]; then
        printf "\r    ${GREEN}[OK]${NC} Worker deployment ready         \n"
    else
        printf "\r    ${YELLOW}[WARN]${NC} Worker deployment taking longer than expected\n"
    fi

    echo ""
    log_info "Pod status:"
    kubectl get pods -n "$NAMESPACE" -o wide 2>/dev/null | sed 's/^/    /'
}

verify_rbac() {
    log_info "Verifying RBAC for OTA upgrades..."

    local RBAC_RELEASE="${1:-$RELEASE_NAME}"
    local SA_NAME="${2:-klyro-edge}"
    local CR_NAME="${RBAC_RELEASE}-helm-manager"
    # Supplementary ClusterRole/CRB — NOT managed by Helm, survives chart upgrades.
    # Required because helm apply can overwrite the helm-managed ClusterRole and remove
    # escalate+bind verbs, leaving the SA unable to restore its own RBAC permissions.
    local ESCALATOR_NAME="${RBAC_RELEASE}-rbac-escalator"

    # Always ensure the supplementary escalator exists regardless of helm-managed RBAC state.
    kubectl apply -f - <<RBAC_EOF >/dev/null 2>&1
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ${ESCALATOR_NAME}
  annotations:
    managed-by: "klyro-install"
rules:
  - apiGroups: ["rbac.authorization.k8s.io"]
    resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete", "bind", "escalate"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ${ESCALATOR_NAME}
  annotations:
    managed-by: "klyro-install"
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: ${ESCALATOR_NAME}
subjects:
  - kind: ServiceAccount
    name: ${SA_NAME}
    namespace: ${NAMESPACE}
RBAC_EOF
    printf "    ${GREEN}[OK]${NC} RBAC escalator bootstrap applied\n"

    if kubectl auth can-i list secrets --namespace="$NAMESPACE" \
        --as "system:serviceaccount:${NAMESPACE}:${SA_NAME}" >/dev/null 2>&1; then
        printf "    ${GREEN}[OK]${NC} Agent can read Helm release secrets\n"
        return 0
    fi

    log_warn "Agent ServiceAccount cannot read secrets — applying RBAC fix..."

    if ! kubectl get clusterrole "$CR_NAME" >/dev/null 2>&1; then
        log_info "Creating ClusterRole $CR_NAME..."
        kubectl apply -f - <<RBAC_EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ${CR_NAME}
rules:
  - apiGroups: [""]
    resources: ["secrets", "configmaps", "serviceaccounts"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: [""]
    resources: ["pods", "services", "endpoints", "persistentvolumeclaims"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: ["rbac.authorization.k8s.io"]
    resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete", "bind", "escalate"]
  - apiGroups: ["apps"]
    resources: ["deployments", "daemonsets", "replicasets", "statefulsets"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: ["batch"]
    resources: ["jobs", "cronjobs"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: [""]
    resources: ["events"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["namespaces"]
    verbs: ["get", "list", "watch"]
  - apiGroups: [""]
    resources: ["pods", "namespaces", "nodes"]
    verbs: ["get", "watch", "list"]
  - apiGroups: ["apps"]
    resources: ["replicasets", "deployments", "daemonsets", "statefulsets"]
    verbs: ["get", "watch", "list"]
  - apiGroups: ["batch"]
    resources: ["jobs", "cronjobs"]
    verbs: ["get", "watch", "list"]
RBAC_EOF
    fi

    if ! kubectl get clusterrolebinding "$CR_NAME" >/dev/null 2>&1; then
        log_info "Creating ClusterRoleBinding $CR_NAME..."
        kubectl apply -f - <<RBAC_EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ${CR_NAME}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: ${CR_NAME}
subjects:
  - kind: ServiceAccount
    name: ${SA_NAME}
    namespace: ${NAMESPACE}
RBAC_EOF
    fi

    sleep 2
    if kubectl auth can-i list secrets --namespace="$NAMESPACE" \
        --as "system:serviceaccount:${NAMESPACE}:${SA_NAME}" >/dev/null 2>&1; then
        printf "    ${GREEN}[OK]${NC} RBAC fixed — agent can read Helm release secrets\n"
    else
        log_warn "RBAC still not working after applying fix"
        log_warn "OTA self-upgrade will not work until RBAC is resolved"
        log_warn "Debug: kubectl get clusterrole $CR_NAME -o yaml"
    fi
}

# =============================================================================
# Components: Researcher and MC (Managed Connector)
# =============================================================================

begin_step() {
    echo ""
    printf "${BLUE}Step ${STEP_CURRENT}/${STEP_TOTAL}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "$1"
    STEP_CURRENT=$((STEP_CURRENT + 1))
}

product_has() {
    [ "$PRODUCT" = "both" ] || [ "$PRODUCT" = "$1" ]
}

tty_available() {
    ( : </dev/tty ) 2>/dev/null
}

# Splits the --product (or KLYRO_PRODUCT) list in PRODUCT into the cluster products,
# PRODUCT researcher, mc, both, or none (the klyro CLI alone), and CLI_INSTALL: on when
# the list names cli, off when it does not. Unset leaves both empty: the default,
# researcher,mc,cli with the CLI skipped when it has no user. both is researcher,mc.
parse_product_list() {
    local list item rest r="" m="" c=""
    list=$(printf '%s' "$PRODUCT" | tr -d '[:space:]')
    PRODUCT_LABEL="${list:-researcher,mc,cli (default)}"
    [ -n "$list" ] || { PRODUCT=""; return 0; }
    if [ "$list" = both ]; then
        PRODUCT=both CLI_INSTALL=off
        return 0
    fi
    case ",$list," in
        *,,*)
            log_error "--product has an empty entry (got: $list): researcher, mc and cli, comma-separated"
            exit 1
            ;;
    esac
    rest="$list,"
    while [ -n "$rest" ]; do
        item="${rest%%,*}" rest="${rest#*,}"
        case "$item" in
            researcher|mc|cli)
                case " $r$m$c " in
                    *" $item "*)
                        log_error "--product names $item twice (got: $list)"
                        exit 1
                        ;;
                esac
                case "$item" in
                    researcher) r="researcher " ;;
                    mc) m="mc " ;;
                    cli) c="cli " ;;
                esac
                ;;
            both)
                log_error "--product both cannot be combined with other entries (got: $list): name them, e.g. researcher,mc,cli"
                exit 1
                ;;
            *)
                log_error "--product must be a comma-separated list of researcher, mc and cli, or both (got: $list)"
                exit 1
                ;;
        esac
    done
    if [ -n "$r" ] && [ -n "$m" ]; then
        PRODUCT=both
    elif [ -n "$r" ]; then
        PRODUCT=researcher
    elif [ -n "$m" ]; then
        PRODUCT=mc
    else
        PRODUCT=none
    fi
    if [ -n "$c" ]; then CLI_INSTALL=on; else CLI_INSTALL=off; fi
}

# Succeeds when this run may install the MC: unset PRODUCT defaults to it.
mc_requested() {
    [ -z "$PRODUCT" ] || product_has mc
}

check_product_flags() {
    parse_product_list
    case "$MC_DB_MODE" in
        ""|bundled|external) ;;
        *)
            log_error "--mc-database must be bundled or external (got: $MC_DB_MODE)"
            exit 1
            ;;
    esac
    if [ -n "$MC_DB_URL_FILE" ]; then
        if [ "$MC_DB_MODE" = "bundled" ]; then
            log_error "--mc-database-url-file cannot be combined with --mc-database bundled"
            exit 1
        fi
        MC_DB_MODE="external"
    fi
    if [ "$is_local" = "true" ] || [ "$is_reinstall" = "true" ]; then
        if [ "$PRODUCT" != "researcher" ] && [ -n "$PRODUCT" ] || [ "${CLI_INSTALL:-}" = "on" ]; then
            log_error "--product $PRODUCT_LABEL is not supported with --local or --reinstall: those install the Researcher only"
            exit 1
        fi
        PRODUCT="researcher"
        if [ -n "${CLI_USER_FLAG:-}" ]; then
            log_error "--cli-user needs the klyro CLI, and --local and --reinstall do not install it"
            exit 1
        fi
        CLI_INSTALL=off
    elif [ "${CLI_INSTALL:-}" = "off" ] && [ -n "${CLI_USER_FLAG:-}" ]; then
        log_error "--cli-user needs the klyro CLI: add cli to --product (got: $PRODUCT_LABEL)"
        exit 1
    fi
    check_scim_flags
    check_credential_store_flags
}

# Checks --credential-store / --no-credential-store on their own.
check_credential_store_flags() {
    local flag
    [ -n "${MC_CREDENTIAL_STORE_FLAG:-}" ] || return 0
    if [ "$MC_CREDENTIAL_STORE_FLAG" = "conflict" ]; then
        log_error "--credential-store cannot be combined with --no-credential-store"
        exit 1
    fi
    if [ "$is_local" = "true" ] || [ "$is_reinstall" = "true" ] || ! mc_requested; then
        if [ "$MC_CREDENTIAL_STORE_FLAG" = "off" ]; then flag="--no-credential-store"; else flag="--credential-store"; fi
        log_error "$flag needs the MC, and this run does not install it (--product without mc, --local or --reinstall)"
        exit 1
    fi
}

# Prints the first --scim-* flag given on this run other than --no-scim-ingress, or nothing.
scim_flag_given() {
    if [ -n "${MC_SCIM_HOST:-}" ]; then echo "--scim-host"
    elif [ -n "${MC_SCIM_INGRESS_CLASS:-}" ]; then echo "--scim-ingress-class"
    elif [ -n "${MC_SCIM_TLS_SECRET:-}" ]; then echo "--scim-tls-secret"
    elif [ -n "${MC_SCIM_TLS_CERT:-}" ]; then echo "--scim-tls-cert"
    elif [ -n "${MC_SCIM_TLS_KEY:-}" ]; then echo "--scim-tls-key"
    fi
}

# A DNS name with at least two labels, lowercase letters, digits and hyphens, the
# last label not all digits (an Ingress host cannot be an IP address), at most 253
# characters and 63 per label: no scheme, port, path or wildcard.
valid_scim_host() {
    [ "${#1}" -le 253 ] || return 1
    printf '%s\n' "$1" | grep -Eq '^([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)+[a-z0-9]([-a-z0-9]*[a-z0-9])?$' || return 1
    ! printf '%s\n' "$1" | grep -Eq '[^.]{64}' || return 1
    printf '%s\n' "${1##*.}" | grep -Eq '[a-z-]'
}

# A Kubernetes object name (DNS-1123 subdomain).
valid_k8s_name() {
    [ "${#1}" -le 253 ] && printf '%s\n' "$1" | grep -Eq '^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$'
}

# Checks the --scim-* flags on their own; resolve_mc_scim checks them against the cluster.
check_scim_flags() {
    local flag
    flag=$(scim_flag_given)
    if [ "${MC_NO_SCIM_INGRESS:-}" = "true" ]; then
        if [ -n "$flag" ]; then
            log_error "--no-scim-ingress cannot be combined with $flag"
            exit 1
        fi
        flag="--no-scim-ingress"
    fi
    [ -n "$flag" ] || return 0
    if [ "$is_local" = "true" ] || [ "$is_reinstall" = "true" ] || ! mc_requested; then
        log_error "$flag needs the MC, and this run does not install it (--product without mc, --local or --reinstall)"
        echo "  Expose SCIM on an install whose --product includes mc (the default does)."
        exit 1
    fi
    [ "${MC_NO_SCIM_INGRESS:-}" != "true" ] || return 0
    if [ -z "${MC_SCIM_HOST:-}" ]; then
        log_error "$flag needs --scim-host"
        exit 1
    fi
    MC_SCIM_HOST=$(printf '%s' "$MC_SCIM_HOST" | tr '[:upper:]' '[:lower:]')
    if ! valid_scim_host "$MC_SCIM_HOST"; then
        log_error "--scim-host must be a DNS name such as scim.example.com, with no scheme, port, path or wildcard, and not an IP address (got: $MC_SCIM_HOST)"
        exit 1
    fi
    if [ -n "${MC_SCIM_INGRESS_CLASS:-}" ] && ! valid_k8s_name "$MC_SCIM_INGRESS_CLASS"; then
        log_error "--scim-ingress-class must be an IngressClass name (got: $MC_SCIM_INGRESS_CLASS)"
        exit 1
    fi
    if [ -n "${MC_SCIM_TLS_SECRET:-}" ]; then
        if [ -n "${MC_SCIM_TLS_CERT:-}${MC_SCIM_TLS_KEY:-}" ]; then
            log_error "--scim-tls-secret cannot be combined with --scim-tls-cert / --scim-tls-key"
            exit 1
        fi
        if ! valid_k8s_name "$MC_SCIM_TLS_SECRET"; then
            log_error "--scim-tls-secret must be a Secret name (got: $MC_SCIM_TLS_SECRET)"
            exit 1
        fi
    fi
    if [ -n "${MC_SCIM_TLS_CERT:-}" ] && [ -z "${MC_SCIM_TLS_KEY:-}" ]; then
        log_error "--scim-tls-cert needs --scim-tls-key"
        exit 1
    fi
    if [ -n "${MC_SCIM_TLS_KEY:-}" ] && [ -z "${MC_SCIM_TLS_CERT:-}" ]; then
        log_error "--scim-tls-key needs --scim-tls-cert"
        exit 1
    fi
    return 0
}

resolve_product() {
    if [ -z "$PRODUCT" ]; then
        PRODUCT="both"
        # An MC database or SCIM flag asks for the MC: no Researcher-only fallback then.
        [ -n "$MC_DB_MODE" ] || [ -n "${MC_SCIM_HOST:-}" ] || PRODUCT_DEFAULTED=true
        MC_DB_MODE="${MC_DB_MODE:-bundled}"
    fi
    case "$PRODUCT" in
        researcher) log_info "Components: Researcher" ;;
        mc)         log_info "Components: MC" ;;
        both)       log_info "Components: Researcher and MC" ;;
    esac
}

read_mc_database_url_from_tty() {
    local url=""
    printf "PostgreSQL URL for the MC (input hidden), e.g. postgres://user:password@host:5432/mc?sslmode=require\n> " >/dev/tty
    trap 'stty echo </dev/tty 2>/dev/null; exit 130' INT TERM
    stty -echo </dev/tty 2>/dev/null || true
    IFS= read -r url </dev/tty || url=""
    stty echo </dev/tty 2>/dev/null || true
    trap - INT TERM
    echo "" >/dev/tty
    MC_DB_URL="$url"
}

resolve_mc_database() {
    local answer=""
    if [ -z "$MC_DB_MODE" ]; then
        if [ "${PREFLIGHT:-}" != "true" ] && tty_available; then
            {
                echo ""
                echo "Where should the MC keep its database?"
                echo "  1) Bundled PostgreSQL on a persistent volume in this cluster (default)"
                echo "  2) Your own PostgreSQL: you provide a connection URL"
            } >/dev/tty
            printf "> " >/dev/tty
            IFS= read -r answer </dev/tty || answer=""
            case "$answer" in
                2|external) MC_DB_MODE="external" ;;
                *)          MC_DB_MODE="bundled" ;;
            esac
        else
            MC_DB_MODE="bundled"
        fi
    fi

    if [ "$MC_DB_MODE" = "external" ]; then
        if [ -n "$MC_DB_URL_FILE" ]; then
            if [ ! -r "$MC_DB_URL_FILE" ]; then
                log_error "Cannot read the MC database URL file: $MC_DB_URL_FILE"
                exit 1
            fi
            MC_DB_URL=$(cat "$MC_DB_URL_FILE")
            MC_DB_URL=$(printf '%s' "$MC_DB_URL" | tr -d '\r\n')
        elif [ "${PREFLIGHT:-}" != "true" ] && tty_available; then
            read_mc_database_url_from_tty
        else
            log_error "--mc-database external needs --mc-database-url-file <path> when there is no terminal"
            exit 1
        fi
        case "$MC_DB_URL" in
            postgres://*|postgresql://*) ;;
            "")
                log_error "No MC database URL given"
                exit 1
                ;;
            *)
                log_error "The MC database URL must start with postgres:// or postgresql://"
                exit 1
                ;;
        esac
    fi
    log_info "MC database: $MC_DB_MODE"
}

# Sets HOST_FQDN to this machine's lowercased DNS name; succeeds when that name or its
# first label is a node of the cluster.
host_is_cluster_node() {
    local nodes
    HOST_FQDN=$(hostname -f 2>/dev/null || hostname 2>/dev/null || true)
    HOST_FQDN=$(printf '%s' "$HOST_FQDN" | tr '[:upper:]' '[:lower:]')
    nodes=$(kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null | tr '[:upper:]' '[:lower:]' || true)
    [ -n "$HOST_FQDN" ] && printf '%s\n' "$nodes" | grep -qxF -e "$HOST_FQDN" -e "${HOST_FQDN%%.*}"
}

# Prints firewalld's zone for the default route's interface, else the default zone,
# else nothing; firewall-cmd runs through $1 (such as k3s_root) when given.
default_route_zone() {
    local run="${1:-command}" iface zone=""
    iface=$(ip -o route show default 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "dev") { print $(i + 1); exit }}' || true)
    if [ -n "$iface" ]; then
        zone=$($run firewall-cmd --get-zone-of-interface="$iface" 2>/dev/null) || zone=""
    fi
    if [ -z "$zone" ]; then
        zone=$($run firewall-cmd --get-default-zone 2>/dev/null) || zone=""
    fi
    printf '%s\n' "$zone"
}

# Warns when a running firewalld on this node does not allow https (443/tcp) in the zone
# of the default route's interface, so the SCIM Ingress is unreachable from off the host.
# Never changes the firewall: SCIM_FIREWALL_FIX holds the command for the summary.
check_scim_firewall() {
    local zone target
    SCIM_FIREWALL_FIX=""
    command -v firewall-cmd >/dev/null 2>&1 || return 0
    [ "$(firewall-cmd --state 2>/dev/null || true)" = "running" ] || return 0
    host_is_cluster_node || return 0
    zone=$(default_route_zone)
    if [ -n "$zone" ]; then
        firewall-cmd --zone="$zone" --query-service=https >/dev/null 2>&1 && return 0
        firewall-cmd --zone="$zone" --query-port=443/tcp >/dev/null 2>&1 && return 0
        target=$(firewall-cmd --info-zone="$zone" 2>/dev/null | sed -n 's/^[[:space:]]*target:[[:space:]]*//p' || true)
        [ "$target" = "ACCEPT" ] && return 0
        SCIM_FIREWALL_FIX="firewall-cmd --permanent --zone=$zone --add-service=https && firewall-cmd --reload"
    else
        SCIM_FIREWALL_FIX="firewall-cmd --permanent --add-service=https && firewall-cmd --reload"
    fi
    printf "    ${YELLOW}[WARN]${NC} firewalld on this node does not allow https (443/tcp) in zone %s: the IGA cannot reach https://%s. The installer changes the host firewall only when --bootstrap installs k3s on this host; to open it, run: %s\n" \
        "${zone:-unknown}" "$MC_SCIM_HOST" "$SCIM_FIREWALL_FIX"
}

# The firewall-cmd commands that put each CIDR of $1 in firewalld's trusted zone; $2 lists
# the CIDRs already bound to another zone, which are moved instead.
trusted_sources_fix() {
    local cidr verb fix=""
    for cidr in $1; do
        verb=add
        case " ${2:-} " in *" $cidr "*) verb=change ;; esac
        fix="${fix}firewall-cmd --permanent --zone=trusted --${verb}-source=$cidr && "
    done
    printf '%s\n' "${fix}firewall-cmd --reload"
}

# Succeeds when firewalld zone $1 is trusted or has target ACCEPT, in the runtime
# configuration, or with $2 = --permanent in the permanent one.
zone_accepts() {
    local target
    [ -n "$1" ] || return 1
    [ "$1" = "trusted" ] && return 0
    if [ "${2:-}" = "--permanent" ]; then
        target=$(as_root firewall-cmd --permanent --zone="$1" --get-target 2>/dev/null || true)
    else
        target=$(as_root firewall-cmd --info-zone="$1" 2>/dev/null | sed -n 's/^[[:space:]]*target:[[:space:]]*//p' || true)
    fi
    [ "$target" = "ACCEPT" ]
}

# Sets EV_STATUS warn, with the commands in EV_FIX, when a running firewalld on this node
# does not trust the pod and service networks (POD_NETWORK_CIDRS) in both its runtime and
# permanent configuration: it then drops traffic between pods, and Temporal never forms
# its ringpop cluster. With PF_ASSUME_NODE=true, this host is judged as a node; with
# PF_NOROOT=true, a running firewalld is skip (not verified). Never changes the firewall.
eval_pod_network_firewall() {
    local cidr rzone pzone missing="" add="" moved=""
    EV_STATUS=ok EV_FIX=""
    if ! command -v firewall-cmd >/dev/null 2>&1; then
        EV_DETAIL="not installed"
        return 0
    fi
    if [ "$(firewall-cmd --state 2>/dev/null || true)" != "running" ]; then
        EV_DETAIL="not running"
        return 0
    fi
    if [ "${PF_ASSUME_NODE:-}" != "true" ] && ! host_is_cluster_node; then
        EV_DETAIL="this host is not a node of the cluster"
        return 0
    fi
    if [ "${PF_NOROOT:-}" = "true" ]; then
        EV_STATUS=skip EV_DETAIL="not verified (needs root)"
        return 0
    fi
    for cidr in $POD_NETWORK_CIDRS; do
        rzone=$(as_root firewall-cmd --get-zone-of-source="$cidr" 2>/dev/null) || rzone=""
        pzone=$(as_root firewall-cmd --permanent --get-zone-of-source="$cidr" 2>/dev/null) || pzone=""
        if zone_accepts "$pzone" --permanent; then
            zone_accepts "$rzone" && continue
        else
            [ -z "$pzone" ] || moved="$moved $cidr"
            add="$add $cidr"
        fi
        missing="$missing $cidr"
    done
    if [ -z "$missing" ]; then
        EV_DETAIL="the pod and service networks are trusted"
        return 0
    fi
    EV_STATUS=warn EV_FIX=$(trusted_sources_fix "$add" "$moved")
    EV_DETAIL="firewalld on this node does not trust the pod and service networks (${missing# }): it drops traffic between pods, Temporal crash-loops (ringpop join duration exceeded) and the install waits until it times out."
}

# Warns when eval_pod_network_firewall does; POD_FIREWALL_FIX holds this node's commands
# for the summary.
check_pod_network_firewall() {
    eval_pod_network_firewall
    POD_FIREWALL_FIX=""
    [ "$EV_STATUS" = "warn" ] || return 0
    POD_FIREWALL_FIX="$EV_FIX"
    log_warn "$EV_DETAIL"
    echo "  The installer changes the host firewall only when --bootstrap installs k3s on this host. Before installing, as root, run:"
    echo "    $POD_FIREWALL_FIX"
}

# Prints the firewalld fix when an MC Temporal pod's log shows ringpop failing to join,
# the sign of a node firewall that drops traffic between pods.
mc_ringpop_hint() {
    local selector="app.kubernetes.io/instance=${MC_RELEASE_NAME},app.kubernetes.io/part-of=temporal" pods pod
    pods=$(kubectl get pods -n "$NAMESPACE" -l "$selector" --request-timeout=10s \
        -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null) || return 0
    for pod in $pods; do
        if { kubectl logs -n "$NAMESPACE" "$pod" --all-containers --tail=200 --request-timeout=10s 2>/dev/null
            kubectl logs -n "$NAMESPACE" "$pod" --all-containers --tail=200 --previous --request-timeout=10s 2>/dev/null
        } | grep -i ringpop | grep -q 'join duration exceeded'; then
            echo ""
            printf "    ${YELLOW}[HINT]${NC} Temporal pod %s cannot join its ringpop cluster: the node's firewalld most likely drops traffic between pods.\n" "$pod"
            echo "    On each node, trust the pod and service networks as root (--change-source for a network already bound to another zone), then re-run the installer:"
            echo "      $(trusted_sources_fix "$POD_NETWORK_CIDRS")"
            return 0
        fi
    done
}

# Settles the SCIM ingress before the token is redeemed. Direct ingress is on only for a
# host someone chose: --no-scim-ingress, else this run's --scim-* flags, else what the
# last install saved in ConfigMap klyro-mc-agent-info, else the relay through Klyro Cloud.
# MC_SCIM_STATE (on, off, or empty for the relay default) is saved for the next run.
resolve_mc_scim() {
    local cm="${MC_RELEASE_NAME}-agent-info"
    if [ "$MC_NO_SCIM_INGRESS" = "true" ]; then
        MC_SCIM_STATE="off"
        log_info "SCIM ingress: off (--no-scim-ingress)"
        return 0
    fi
    if [ -z "$MC_SCIM_HOST" ]; then
        if [ "$(kubectl get configmap "$cm" -n "$NAMESPACE" -o jsonpath='{.data.scim-ingress}' 2>/dev/null || true)" = "off" ]; then
            MC_SCIM_STATE="off"
            log_info "SCIM ingress: off, as the previous install left it (ConfigMap $cm); pass --scim-host to turn it on"
            return 0
        fi
        MC_SCIM_HOST=$(kubectl get configmap "$cm" -n "$NAMESPACE" -o jsonpath='{.data.scim-host}' 2>/dev/null || true)
        if [ -n "$MC_SCIM_HOST" ]; then
            MC_SCIM_INGRESS_CLASS=$(kubectl get configmap "$cm" -n "$NAMESPACE" -o jsonpath='{.data.scim-ingress-class}' 2>/dev/null || true)
            MC_SCIM_TLS_SECRET=$(kubectl get configmap "$cm" -n "$NAMESPACE" -o jsonpath='{.data.scim-tls-secret}' 2>/dev/null || true)
            log_info "SCIM ingress kept from the previous install (ConfigMap $cm): $MC_SCIM_HOST"
            if [ -n "$MC_SCIM_TLS_SECRET" ] && ! kubectl get secret "$MC_SCIM_TLS_SECRET" -n "$NAMESPACE" >/dev/null 2>&1; then
                log_warn "The previous install's TLS Secret $MC_SCIM_TLS_SECRET is not in $NAMESPACE: recreate it, or re-run with --scim-host $MC_SCIM_HOST${MC_SCIM_INGRESS_CLASS:+ --scim-ingress-class $MC_SCIM_INGRESS_CLASS} --scim-tls-cert <file> --scim-tls-key <file>"
            fi
            check_scim_flags
        else
            MC_SCIM_STATE=""
            log_info "SCIM: through the Klyro relay; pass --scim-host <dns name your IGA reaches> for direct ingress"
            return 0
        fi
    fi
    MC_SCIM_STATE="on"
    if [ -n "$MC_SCIM_TLS_CERT" ]; then
        if [ ! -r "$MC_SCIM_TLS_CERT" ] || ! grep -q -- '-----BEGIN CERTIFICATE-----' "$MC_SCIM_TLS_CERT"; then
            log_error "--scim-tls-cert $MC_SCIM_TLS_CERT is not a readable PEM certificate"
            exit 1
        fi
        if [ ! -r "$MC_SCIM_TLS_KEY" ] || ! grep -Eq -- '-----BEGIN ([A-Z]+ )?PRIVATE KEY-----' "$MC_SCIM_TLS_KEY"; then
            log_error "--scim-tls-key $MC_SCIM_TLS_KEY is not a readable PEM private key"
            exit 1
        fi
        if ! kubectl create secret tls "$MC_SCIM_TLS_SECRET_DEFAULT" --cert="$MC_SCIM_TLS_CERT" \
            --key="$MC_SCIM_TLS_KEY" --dry-run=client -o name >/dev/null; then
            log_error "--scim-tls-cert and --scim-tls-key are not a matching certificate and key"
            exit 1
        fi
        MC_SCIM_TLS_SECRET="$MC_SCIM_TLS_SECRET_DEFAULT"
    fi
    log_info "SCIM ingress: https://${MC_SCIM_HOST}/api/v1/applications/ (IngressClass ${MC_SCIM_INGRESS_CLASS:-cluster default}, TLS Secret ${MC_SCIM_TLS_SECRET:-none})"
    if [ -z "$MC_SCIM_TLS_SECRET" ]; then
        log_warn "No --scim-tls-secret or --scim-tls-cert: the ingress controller answers https://${MC_SCIM_HOST} with its own default certificate (self-signed on k3s), which an IGA does not trust"
    fi
}

# Reports where the SCIM Ingress is served, after the MC chart is installed. Never fatal:
# the Ingress and its certificate can be fixed without reinstalling.
# Settles the credential store: --no-credential-store or --credential-store, else what the last
# install saved in ConfigMap klyro-mc-agent-info, else on. A read of that ConfigMap that fails
# for any reason but NotFound stops the install rather than turning a saved opt-out back on. MC_CREDENTIAL_STORE (on or off) is
# saved for the next run.
resolve_mc_credential_store() {
    local cm="${MC_RELEASE_NAME}-agent-info" saved="" err
    case "${MC_CREDENTIAL_STORE_FLAG:-}" in
        off)
            MC_CREDENTIAL_STORE="off"
            log_info "Credential store: off (--no-credential-store)"
            return 0
            ;;
        on)
            MC_CREDENTIAL_STORE="on"
            ;;
        *)
            err=$(mktemp)
            if ! saved=$(kubectl get configmap "$cm" -n "$NAMESPACE" -o jsonpath='{.data.credential-store}' 2>"$err"); then
                if ! grep -q NotFound "$err"; then
                    log_error "cannot read the saved credential store choice from ConfigMap $cm: $(cat "$err")"
                    echo "  Fix cluster access and re-run, or pass --credential-store or --no-credential-store."
                    rm -f "$err"
                    exit 1
                fi
                saved=""
            fi
            rm -f "$err"
            if [ "$saved" = "off" ]; then
                MC_CREDENTIAL_STORE="off"
                log_info "Credential store: off, as the previous install left it (ConfigMap $cm); pass --credential-store to turn it on"
                return 0
            fi
            MC_CREDENTIAL_STORE="on"
            ;;
    esac
    log_info "Credential store: Secret ${MC_RELEASE_NAME}-credentials, written by the MC agent and the squad (ServiceAccount ${MC_RELEASE_NAME}-squad); --no-credential-store turns it off"
}

verify_mc_scim_ingress() {
    local ing="${MC_RELEASE_NAME}-scim" class addr="" t=0
    [ -n "$MC_SCIM_HOST" ] || return 0
    echo ""
    if ! kubectl get ingress "$ing" -n "$NAMESPACE" >/dev/null 2>&1; then
        printf "    ${YELLOW}[WARN]${NC} Ingress %s not found: this MC chart version may predate scim.ingress\n" "$ing"
        return 0
    fi
    class=$(kubectl get ingress "$ing" -n "$NAMESPACE" -o jsonpath='{.spec.ingressClassName}' 2>/dev/null || true)
    if [ -z "$class" ]; then
        printf "    ${YELLOW}[WARN]${NC} Ingress %s has no IngressClass and the cluster has no default one: pass --scim-ingress-class\n" "$ing"
    elif ! kubectl get ingressclass "$class" >/dev/null 2>&1; then
        printf "    ${YELLOW}[WARN]${NC} IngressClass %s is not in the cluster: no controller serves Ingress %s yet\n" "$class" "$ing"
    fi
    if [ -n "$MC_SCIM_TLS_SECRET" ] && ! kubectl get secret "$MC_SCIM_TLS_SECRET" -n "$NAMESPACE" >/dev/null 2>&1; then
        printf "    ${YELLOW}[WARN]${NC} TLS Secret %s is not in %s: create it (kubectl create secret tls %s --cert=... --key=... -n %s)\n" \
            "$MC_SCIM_TLS_SECRET" "$NAMESPACE" "$MC_SCIM_TLS_SECRET" "$NAMESPACE"
    fi
    while [ "$t" -lt 12 ]; do
        addr=$(kubectl get ingress "$ing" -n "$NAMESPACE" \
            -o jsonpath='{range .status.loadBalancer.ingress[*]}{.ip}{.hostname} {end}' 2>/dev/null || true)
        [ -n "$addr" ] && break
        t=$((t + 1))
        sleep 5
    done
    if [ -n "$addr" ]; then
        printf "    ${GREEN}[OK]${NC} SCIM Ingress %s (class %s) served at %s: point DNS for %s there\n" "$ing" "${class:-none}" "$addr" "$MC_SCIM_HOST"
    else
        printf "    ${YELLOW}[WARN]${NC} SCIM Ingress %s has no address yet: check the ingress controller (kubectl get ingress %s -n %s)\n" "$ing" "$ing" "$NAMESPACE"
    fi
    check_scim_firewall
}

# Writes the external database URL to the Secret the MC worker reads, from stdin so
# the URL never appears in a process argument list or a Helm value.
write_mc_database_secret() {
    local encoded
    encoded=$(printf '%s' "$MC_DB_URL" | base64 | tr -d '\n')
    kubectl apply -f - >/dev/null <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: ${MC_DB_EXTERNAL_SECRET}
  namespace: ${NAMESPACE}
  labels:
    app.kubernetes.io/part-of: ${MC_RELEASE_NAME}
type: Opaque
data:
  url: ${encoded}
EOF
    printf "    ${GREEN}[OK]${NC} Secret: ${MC_DB_EXTERNAL_SECRET} (key url)\n"
}

# Proves the URL's user can create, alter and drop a table in its default schema,
# inside a transaction that is rolled back, from a short-lived pod in the cluster
# (the network the MC worker will connect from).
validate_mc_external_database() {
    local pod="klyro-mc-db-check" phase="" t=0 out
    create_namespace
    write_mc_database_secret

    kubectl delete pod "$pod" -n "$NAMESPACE" --ignore-not-found --wait=true >/dev/null 2>&1 || true
    kubectl apply -f - >/dev/null <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: ${pod}
  namespace: ${NAMESPACE}
  labels:
    app.kubernetes.io/part-of: ${MC_RELEASE_NAME}
spec:
  restartPolicy: Never
  securityContext:
    runAsNonRoot: true
    runAsUser: 70
    runAsGroup: 70
    seccompProfile:
      type: RuntimeDefault
  containers:
    - name: psql
      image: ${REGISTRY_PREFIX}library/postgres:16.4-alpine
      env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: ${MC_DB_EXTERNAL_SECRET}
              key: url
        - name: PGCONNECT_TIMEOUT
          value: "15"
      command: ["sh", "-c"]
      args:
        - |
          psql "\$DATABASE_URL" -X -q -At -v ON_ERROR_STOP=1 <<'SQL'
          SELECT 'connected as ' || current_user || ', schema ' || coalesce(current_schema(), '(none)');
          BEGIN;
          DO \$chk\$
          BEGIN
            IF current_schema() IS NULL THEN
              RAISE EXCEPTION 'no usable schema on the search_path of user %', current_user;
            END IF;
            IF EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = current_schema()
                       AND tablename = 'schema_migrations' AND tableowner <> current_user) THEN
              RAISE EXCEPTION 'schema_migrations in schema % belongs to another user', current_schema();
            END IF;
          END
          \$chk\$;
          CREATE TABLE klyro_mc_install_check (id integer PRIMARY KEY);
          ALTER TABLE klyro_mc_install_check ADD COLUMN checked_at timestamptz;
          CREATE INDEX klyro_mc_install_check_idx ON klyro_mc_install_check (checked_at);
          DROP TABLE klyro_mc_install_check;
          ROLLBACK;
          SELECT 'ok: can create, alter and drop tables';
          SQL
      securityContext:
        allowPrivilegeEscalation: false
        capabilities:
          drop: ["ALL"]
      resources:
        requests:
          cpu: 10m
          memory: 32Mi
        limits:
          cpu: 200m
          memory: 128Mi
EOF

    log_info "Checking that the MC database user can create and alter tables..."
    while [ "$t" -lt 90 ]; do
        phase=$(kubectl get pod "$pod" -n "$NAMESPACE" -o jsonpath='{.status.phase}' 2>/dev/null || true)
        case "$phase" in
            Succeeded|Failed) break ;;
        esac
        t=$((t + 1))
        sleep 2
    done
    out=$(kubectl logs "$pod" -n "$NAMESPACE" 2>&1 || true)
    kubectl delete pod "$pod" -n "$NAMESPACE" --ignore-not-found --wait=false >/dev/null 2>&1 || true

    if [ "$phase" = "Succeeded" ]; then
        printf '%s\n' "$out" | sed 's/^/    /'
        log_success "MC database accepted"
        return 0
    fi

    if [ "$phase" != "Failed" ]; then
        log_error "The MC database check did not finish (pod phase: ${phase:-unknown})"
        echo "  The check pod pulls ${REGISTRY_PREFIX}library/postgres:16.4-alpine; check the cluster can pull it."
        exit 1
    fi
    log_error "The MC database URL cannot be used"
    printf '%s\n' "$out" | sed 's/^/    /' >&2
    echo ""
    echo "  The MC applies its own migrations at startup, so the URL's user must own the"
    echo "  MC's schema: it must be able to CREATE, ALTER and DROP tables in its default"
    echo "  schema (the first schema on its search_path), and any existing"
    echo "  schema_migrations table there must belong to it."
    echo "  Fix the user or the URL, then re-run the installer."
    exit 1
}

# A re-run of the MC upgrades the existing klyro-mc release in place: the release, its
# database and the package versions the MC stores stay, and so does everything else the
# chart owns (the squad ServiceAccount and its token). Uninstalling it would recreate
# every object at revision 1, and a run that then fails to redeem the token would leave
# no MC at all. The new token still registers a new agent id (the install API mints one
# per redemption); create_mc_secrets overwrites the credential Secrets with it and
# restart_mc_for_new_credentials restarts the pods that read them. Only a release stuck
# in a pending Helm operation, which no upgrade can take over, is uninstalled first.
# Sets MC_RELEASE_EXISTED.
cleanup_existing_mc_installation() {
    MC_RELEASE_EXISTED=false
    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        if kubectl get helmchart "$MC_RELEASE_NAME" -n kube-system >/dev/null 2>&1; then
            MC_RELEASE_EXISTED=true
            printf "    ${GREEN}[OK]${NC} Existing MC release found: upgrading it in place (database and package store kept)\n"
        else
            printf "    ${GREEN}[OK]${NC} No existing MC release found\n"
        fi
        return 0
    fi
    if ! command -v helm >/dev/null 2>&1 || ! helm status "$MC_RELEASE_NAME" -n "$NAMESPACE" >/dev/null 2>&1; then
        printf "    ${GREEN}[OK]${NC} No existing MC release found\n"
        return 0
    fi
    if [ -z "$(helm list -n "$NAMESPACE" --pending -q --filter "^${MC_RELEASE_NAME}\$" 2>/dev/null)" ]; then
        MC_RELEASE_EXISTED=true
        printf "    ${GREEN}[OK]${NC} Existing MC release found: upgrading it in place (database and package store kept)\n"
        return 0
    fi
    log_warn "MC release $MC_RELEASE_NAME is stuck in a pending Helm operation: uninstalling it first"
    helm uninstall "$MC_RELEASE_NAME" -n "$NAMESPACE" --wait >/dev/null 2>&1 &
    local uninstall_pid=$!
    local uninstall_status=0
    spin_wait "$uninstall_pid" "Uninstalling the stuck MC release..." || uninstall_status=$?
    if [ "$uninstall_status" -eq 0 ]; then
        printf "\r    ${GREEN}[OK]${NC} Stuck MC release uninstalled (database volume kept)\n"
    else
        printf "\r    ${RED}[FAIL]${NC} Failed to uninstall the stuck MC release\n"
        exit 1
    fi
}

# After an in-place upgrade (MC_RELEASE_EXISTED), restarts the MC agent Deployment and
# collector DaemonSet, which read the credential Secrets: a pod reads them at start only, so without it the agent would
# keep running as the agent of the previous token. A first install has nothing to restart.
restart_mc_for_new_credentials() {
    [ "$MC_RELEASE_EXISTED" = "true" ] || return 0
    if kubectl rollout restart deployment,daemonset -n "$NAMESPACE" \
        -l "app.kubernetes.io/instance=${MC_RELEASE_NAME},app.kubernetes.io/component in (agent,otel-collector)" >/dev/null 2>&1; then
        printf "    ${GREEN}[OK]${NC} MC agent restarted with the new credentials\n"
        return 0
    fi
    log_error "Could not restart the MC agent with the new credentials"
    echo "  Run: kubectl rollout restart deployment/${MC_RELEASE_NAME}-agent -n $NAMESPACE"
    exit 1
}

# Redeems the install token for the MC role. One token is redeemable once per role,
# so the same token also installs the Researcher.
fetch_mc_credentials() {
    local response_file http_code response
    response_file=$(mktemp)
    http_code=$(curl -sL -w "%{http_code}" \
        -o "$response_file" \
        "${KLYRO_API_URL}/api/v1/agents/install?token=${INSTALL_TOKEN}&role=mc" \
        -H "User-Agent: klyro-installer/1.0" \
        2>/dev/null) || http_code="000"

    case "$http_code" in
        200|201)
            log_success "Install token validated for the MC"
            ;;
        400)
            log_error "The install API rejected the MC install request (HTTP 400)"
            [ "${KLYRO_DEBUG:-}" = "true" ] && redact_json "$(cat "$response_file")"
            rm -f "$response_file"
            exit 1
            ;;
        401|403)
            log_error "Install token expired or invalid"
            echo "Generate a new token from: https://app.klyro.security/agents/new"
            rm -f "$response_file"
            exit 1
            ;;
        404)
            log_error "Install token not found"
            rm -f "$response_file"
            exit 1
            ;;
        409)
            log_error "This install token has already installed an MC"
            echo "Generate a new token from: https://app.klyro.security/agents/new"
            rm -f "$response_file"
            exit 1
            ;;
        429)
            log_error "Rate limited - please wait and try again"
            rm -f "$response_file"
            exit 1
            ;;
        000)
            log_error "Cannot connect to Klyro Cloud API"
            echo "Endpoint: ${KLYRO_API_URL}"
            rm -f "$response_file"
            exit 1
            ;;
        *)
            log_error "API error (HTTP $http_code)"
            [ "${KLYRO_DEBUG:-}" = "true" ] && redact_json "$(cat "$response_file")"
            rm -f "$response_file"
            exit 1
            ;;
    esac

    response=$(cat "$response_file")
    rm -f "$response_file"

    MC_AGENT_ID=$(json_value "$response" "agent_id")
    MC_TENANT_ID=$(json_value "$response" "tenant_id")
    MC_SITE_ID=$(json_value "$response" "site_id")
    MC_CHART_VERSION=$(json_value "$response" "chart_version")
    MC_OAUTH2_CLIENT_ID=$(json_value "$response" "oauth2_client_id")
    MC_OAUTH2_CLIENT_SECRET=$(json_value "$response" "oauth2_client_secret")
    MC_GRPC_ENDPOINT=$(json_value "$response" "grpc_endpoint")
    MC_AUTH_ENDPOINT=$(json_value "$response" "auth_endpoint")
    MC_GRPC_ENDPOINT="${MC_GRPC_ENDPOINT:-$GRPC_ENDPOINT}"
    MC_AUTH_ENDPOINT="${MC_AUTH_ENDPOINT:-$AUTH_ENDPOINT}"

    if [ -z "$MC_AGENT_ID" ] || [ -z "$MC_OAUTH2_CLIENT_ID" ] || [ -z "$MC_OAUTH2_CLIENT_SECRET" ]; then
        log_error "Incomplete MC response from API - missing required credentials"
        [ "${KLYRO_DEBUG:-}" = "true" ] && echo "Response: $(redact_json "$response")"
        exit 1
    fi

    if [ -n "$MC_CHART_VERSION_OVERRIDE" ]; then
        if [ -n "$MC_CHART_VERSION" ] && [ "$MC_CHART_VERSION" != "$MC_CHART_VERSION_OVERRIDE" ]; then
            log_warn "Using --mc-chart-version $MC_CHART_VERSION_OVERRIDE instead of Klyro Cloud's $MC_CHART_VERSION"
        fi
        MC_CHART_VERSION="$MC_CHART_VERSION_OVERRIDE"
    fi
    resolve_mc_chart
    if [ -z "$MC_CHART_VERSION" ] && [ "$MC_CHART_SOURCE" = "oci" ]; then
        if [ "$PRODUCT_DEFAULTED" = "true" ]; then
            log_warn "MC is not available in this environment yet (no MC chart registered): installing the Researcher only."
            echo "  Re-run with --product mc once it is available. This token's MC install is now used:"
            echo "  adding the MC later needs a new install token."
            PRODUCT="researcher"
            STEP_TOTAL=$((STEP_TOTAL - 1))
            return 0
        fi
        log_error "Klyro Cloud has no MC chart version registered for this environment"
        echo "  Its install response carried an empty chart_version for the MC."
        echo "  Re-run with --mc-chart-version <version> to name the published mc chart"
        echo "  version to install. This token's MC install is now used: mint a new token,"
        echo "  or ask Klyro support to register the mc chart."
        exit 1
    fi

    echo ""
    echo "    ┌─────────────────────────────────────────────────────┐"
    echo "    │  MC Agent ID:   $MC_AGENT_ID"
    echo "    │  Tenant ID:     $MC_TENANT_ID"
    echo "    │  Site ID:       $MC_SITE_ID"
    if [ "$MC_CHART_SOURCE" = "local" ]; then
        echo "    │  Chart:         local charts/mc"
    else
        echo "    │  Chart Version: $MC_CHART_VERSION"
    fi
    echo "    └─────────────────────────────────────────────────────┘"
}

# Picks the MC chart: the repository's charts/mc next to this script when present
# and Helm runs it directly, otherwise the published OCI chart.
resolve_mc_chart() {
    local script_dir local_chart
    script_dir="$(cd "$(dirname "$0")" && pwd)"
    local_chart="${script_dir}/../charts/mc"
    if [ -d "$local_chart" ] && [ "$USE_HELM_CONTROLLER" != "true" ]; then
        MC_CHART_SOURCE="local"
        MC_CHART_PATH="$local_chart"
    else
        MC_CHART_SOURCE="oci"
        MC_CHART_PATH="oci://${KLYRO_REGISTRY}/klyrohq/klyro-security/charts/mc"
    fi
}

create_mc_secrets() {
    kubectl create secret generic "${MC_RELEASE_NAME}-cloud-credentials" \
        --from-literal=agent-id="$MC_AGENT_ID" \
        --from-literal=access-token="$MC_OAUTH2_CLIENT_SECRET" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null
    printf "    ${GREEN}[OK]${NC} Secret: ${MC_RELEASE_NAME}-cloud-credentials\n"

    kubectl create secret generic "${MC_RELEASE_NAME}-oauth-credentials" \
        --from-literal=client-id="$MC_OAUTH2_CLIENT_ID" \
        --from-literal=client-secret="$MC_OAUTH2_CLIENT_SECRET" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null
    printf "    ${GREEN}[OK]${NC} Secret: ${MC_RELEASE_NAME}-oauth-credentials\n"

    kubectl create configmap "${MC_RELEASE_NAME}-agent-info" \
        --from-literal=agent-id="$MC_AGENT_ID" \
        --from-literal=tenant-id="$MC_TENANT_ID" \
        --from-literal=site-id="$MC_SITE_ID" \
        --from-literal=grpc-endpoint="$MC_GRPC_ENDPOINT" \
        --from-literal=auth-endpoint="${MC_AUTH_ENDPOINT:-}" \
        --from-literal=database-mode="$MC_DB_MODE" \
        --from-literal=scim-ingress="${MC_SCIM_STATE:-}" \
        --from-literal=scim-host="${MC_SCIM_HOST:-}" \
        --from-literal=scim-ingress-class="${MC_SCIM_INGRESS_CLASS:-}" \
        --from-literal=scim-tls-secret="${MC_SCIM_TLS_SECRET:-}" \
        --from-literal=credential-store="${MC_CREDENTIAL_STORE:-}" \
        --namespace="$NAMESPACE" \
        --dry-run=client -o yaml | kubectl apply -f - >/dev/null
    printf "    ${GREEN}[OK]${NC} ConfigMap: ${MC_RELEASE_NAME}-agent-info\n"

    if [ -n "${MC_SCIM_TLS_CERT:-}" ]; then
        kubectl create secret tls "$MC_SCIM_TLS_SECRET" \
            --cert="$MC_SCIM_TLS_CERT" --key="$MC_SCIM_TLS_KEY" \
            --namespace="$NAMESPACE" \
            --dry-run=client -o yaml | kubectl apply -f - >/dev/null
        printf "    ${GREEN}[OK]${NC} Secret: ${MC_SCIM_TLS_SECRET} (SCIM TLS certificate)\n"
    fi
}

# Where the install points the charts' images: Klyro's own under klyro_image_registry, Docker
# Hub ones through the registry's pull-through mirror (official images under library/).
klyro_image_registry() {
    printf '%s/klyrohq/klyro-security\n' "$KLYRO_REGISTRY"
}

mirror_image_path() {
    case "$1" in
        */*) printf '%s\n' "$1" ;;
        *) printf 'library/%s\n' "$1" ;;
    esac
}

mirror_image_repository() {
    printf '%s/%s\n' "$KLYRO_REGISTRY" "$(mirror_image_path "$1")"
}

# The image values keys of chart $1 (klyro-edge or mc) that install_image_repository maps.
install_image_keys() {
    case "$1" in
        klyro-edge) echo "agent.image worker.image opentelemetry.collector.image" ;;
        mc) echo "agent.image worker.image postgresql.image temporal.server.image temporal.admintools.image opentelemetry.collector.image" ;;
    esac
}

# The repository image $2 (a values key such as agent.image) of chart $1 is pulled from once
# installed, given the chart's own repository $3: the one the install sets, or for the MC's
# agent and worker the global.imageRegistry it sets before the chart's repository, as the
# chart composes them.
install_image_repository() {
    case "$1:$2" in
        klyro-edge:agent.image) echo "$(klyro_image_registry)/klyro-edge" ;;
        klyro-edge:worker.image) echo "$(klyro_image_registry)/klyro-operator" ;;
        *:opentelemetry.collector.image) mirror_image_repository otel/opentelemetry-collector-contrib ;;
        mc:postgresql.image) mirror_image_repository postgres ;;
        mc:temporal.server.image) mirror_image_repository temporalio/server ;;
        mc:temporal.admintools.image) mirror_image_repository temporalio/admin-tools ;;
        mc:agent.image|mc:worker.image)
            case "${3:-}" in
                "") ;;
                */*|*:*) echo "$3" ;;
                *) echo "$(klyro_image_registry)/$3" ;;
            esac
            ;;
    esac
}

write_mc_values() {
    local vals="$1" detected_env="production" otel_ingest_host="otel-ingest.klyro.security"
    local token_url="" default_sc
    case "$MC_GRPC_ENDPOINT" in
        *dev.*)
            detected_env="dev"
            otel_ingest_host="otel-ingest.dev.klyro.security"
            ;;
        *staging.*)
            detected_env="staging"
            otel_ingest_host="otel-ingest.staging.klyro.security"
            ;;
    esac
    if [ -n "$MC_AUTH_ENDPOINT" ]; then
        case "${MC_AUTH_ENDPOINT%/}" in
            */protocol/openid-connect/token) token_url="${MC_AUTH_ENDPOINT%/}" ;;
            */realms/*) token_url="${MC_AUTH_ENDPOINT%/}/protocol/openid-connect/token" ;;
            *)          token_url="${MC_AUTH_ENDPOINT%/}" ;;
        esac
    fi
    default_sc=$(kubectl get storageclass -o jsonpath='{.items[?(@.metadata.annotations.storageclass\.kubernetes\.io/is-default-class=="true")].metadata.name}' 2>/dev/null || true)
    if [ -z "$default_sc" ]; then
        default_sc=$(kubectl get storageclass -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
    fi

    {
        echo "global:"
        echo "  imageRegistry: \"$(klyro_image_registry)\""
        echo "klyroCloud:"
        echo "  endpoint: \"${KLYRO_API_URL}\""
        echo "  gatewayHttpUrl: \"${KLYRO_API_URL}\""
        echo "  grpc:"
        echo "    endpoint: \"${MC_GRPC_ENDPOINT}\""
        echo "agent:"
        echo "  role: mc"
        echo "  persistence:"
        echo "    enabled: true"
        [ -n "$default_sc" ] && echo "    storageClass: \"${default_sc}\""
        echo "  helm:"
        echo "    chartRepo: \"${CHART_REPO:-oci://${KLYRO_REGISTRY}/klyrohq/klyro-security/charts}\""
        echo "worker:"
        echo "  environment: \"${detected_env}\""
        echo "database:"
        echo "  mode: ${MC_DB_MODE}"
        if [ "$MC_DB_MODE" = "external" ]; then
            echo "  external:"
            echo "    existingSecret: \"${MC_DB_EXTERNAL_SECRET}\""
        fi
        if [ -n "${MC_SCIM_HOST:-}" ]; then
            echo "scim:"
            echo "  ingress:"
            echo "    enabled: true"
            echo "    host: \"${MC_SCIM_HOST}\""
            if [ -n "${MC_SCIM_INGRESS_CLASS:-}" ]; then
                echo "    className: \"${MC_SCIM_INGRESS_CLASS}\""
            fi
            if [ -n "${MC_SCIM_TLS_SECRET:-}" ]; then
                echo "    tls:"
                echo "      - hosts:"
                echo "          - \"${MC_SCIM_HOST}\""
                echo "        secretName: \"${MC_SCIM_TLS_SECRET}\""
            fi
        fi
        if [ "${MC_CREDENTIAL_STORE:-}" = "on" ]; then
            echo "secrets:"
            echo "  enabled: true"
            echo "  config:"
            echo "    backends:"
            echo "      k8s-secret: {}"
            echo "  k8sSecret:"
            echo "    secretNames:"
            echo "      - \"${MC_RELEASE_NAME}-credentials\""
            echo "    write: true"
            echo "    squad:"
            echo "      enabled: true"
        fi
        echo "postgresql:"
        echo "  image:"
        echo "    registry: \"${KLYRO_REGISTRY}\""
        echo "    repository: $(mirror_image_path postgres)"
        echo "backup:"
        echo "  s3Image:"
        echo "    registry: \"${KLYRO_REGISTRY}\""
        if [ -n "$default_sc" ]; then
            echo "  persistence:"
            echo "    storageClass: \"${default_sc}\""
        fi
        echo "temporal:"
        echo "  server:"
        echo "    image:"
        echo "      repository: \"$(install_image_repository mc temporal.server.image)\""
        echo "  admintools:"
        echo "    image:"
        echo "      repository: \"$(install_image_repository mc temporal.admintools.image)\""
        echo "opentelemetry:"
        echo "  enabled: true"
        echo "  environment: \"${detected_env}\""
        echo "  clusterName: \"${MC_AGENT_ID}\""
        echo "  tenantId: \"${MC_TENANT_ID}\""
        echo "  siteId: \"${MC_SITE_ID}\""
        echo "  collector:"
        echo "    enabled: true"
        echo "    image:"
        echo "      repository: \"$(install_image_repository mc opentelemetry.collector.image)\""
        echo "    exporters:"
        echo "      prometheus:"
        echo "        enabled: true"
        echo "      remoteOtlp:"
        echo "        enabled: true"
        echo "        endpoint: \"https://${otel_ingest_host}\""
        if [ -n "$token_url" ]; then
            echo "        auth:"
            echo "          tokenUrl: \"${token_url}\""
        fi
        egress_values
    } > "$vals"
}

install_mc_chart() {
    local vals pull_dir chart="$MC_CHART_PATH" out status=0
    vals=$(mktemp)
    write_mc_values "$vals"
    if [ "$MC_CHART_SOURCE" = "local" ]; then
        log_info "Using local MC chart: $MC_CHART_PATH (release $MC_RELEASE_NAME, database $MC_DB_MODE)"
    else
        log_info "MC chart: $MC_CHART_PATH $MC_CHART_VERSION (release $MC_RELEASE_NAME, database $MC_DB_MODE)"
    fi

    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        apply_helm_controller_chart "$MC_RELEASE_NAME" "$MC_CHART_PATH" "$MC_CHART_VERSION" "$vals" abort
        rm -f "$vals"
        return
    fi

    pull_dir=$(mktemp -d)
    out=$(mktemp)
    if [ "$MC_CHART_SOURCE" = "oci" ]; then
        log_info "Fetching MC chart from OCI registry..."
        fetch_oci_chart "$pull_dir" "$MC_CHART_PATH" "$MC_CHART_VERSION" || { rm -rf "$vals" "$pull_dir" "$out"; exit 1; }
        chart=$(find "$pull_dir" -name '*.tgz' | head -1)
        log_success "Chart fetched: $(basename "$chart")"
    fi

    helm upgrade --install "$MC_RELEASE_NAME" "$chart" --namespace "$NAMESPACE" \
        -f "$vals" --wait --timeout 15m >"$out" 2>&1 &
    spin_wait "$!" "Deploying the MC..." || status=$?
    if [ "$status" -ne 0 ]; then
        printf "\r    ${RED}[FAIL]${NC} Deploying the MC      \n"
        log_error "MC Helm installation failed (exit $status)"
        echo ""
        echo "Helm output:"
        cat "$out"
        echo ""
        echo "Debug commands:"
        echo "  kubectl get pods -n $NAMESPACE -l app.kubernetes.io/instance=$MC_RELEASE_NAME"
        echo "  kubectl describe pods -n $NAMESPACE -l app.kubernetes.io/instance=$MC_RELEASE_NAME"
        mc_ringpop_hint
        rm -rf "$vals" "$pull_dir" "$out"
        exit "$status"
    fi
    printf "\r    ${GREEN}[OK]${NC} Deploying the MC      \n"
    rm -rf "$vals" "$pull_dir" "$out"
    log_success "MC Helm chart installed successfully"
}

# Sets MC_VERIFY_ELAPSED to the seconds since MC_VERIFY_START.
mc_verify_tick() {
    MC_VERIFY_ELAPSED=$(($(date +%s) - MC_VERIFY_START))
}

# Waits for the MC's Temporal schema Jobs to complete: on a first install they wait for
# PostgreSQL to start, and the MC agent is not ready before they finish. Spends from
# the MC_VERIFY_TIMEOUT budget it shares with the agent rollout; a failed query counts
# as still pending.
wait_mc_schema_jobs() {
    local selector="app.kubernetes.io/instance=${MC_RELEASE_NAME},app.kubernetes.io/part-of=temporal"
    local jobs line name pending failed unread reported=0
    printf "    ${BLUE}[...]${NC} Waiting for the MC database schema Jobs (up to %ss)\n" "$MC_VERIFY_TIMEOUT"
    while :; do
        pending="" failed="" unread=""
        jobs=$(kubectl get jobs -n "$NAMESPACE" -l "$selector" --request-timeout=10s \
            -o jsonpath='{range .items[*]}{.metadata.name} {range .status.conditions[?(@.status=="True")]}{.type},{end}{"\n"}{end}' 2>/dev/null) \
            || { jobs="" unread=" (the Jobs could not be listed)"; }
        mc_verify_tick
        while read -r line; do
            [ -n "$line" ] || continue
            name=${line%% *}
            case "$line" in
                *Failed,*) failed="$failed $name" ;;
                *Complete,*) ;;
                *) pending="$pending $name" ;;
            esac
        done <<EOF
$jobs
EOF
        [ -z "$failed" ] && [ -z "$pending" ] && [ -z "$unread" ] && break
        if [ -n "$failed" ] || [ "$MC_VERIFY_ELAPSED" -ge "$MC_VERIFY_TIMEOUT" ]; then
            if [ -n "$failed" ]; then
                printf "    ${RED}[FAIL]${NC} MC database schema Job failed:%s\n" "$failed"
            else
                printf "    ${RED}[FAIL]${NC} MC database schema Jobs did not complete in %ss:%s%s\n" "$MC_VERIFY_TIMEOUT" "$pending" "$unread"
            fi
            log_error "The MC's Temporal schema setup did not finish. Debug with:"
            for name in $failed $pending; do
                echo "  kubectl logs -n $NAMESPACE job/$name --all-containers"
            done
            echo "  kubectl get pods -n $NAMESPACE -l app.kubernetes.io/instance=${MC_RELEASE_NAME}"
            echo "  kubectl logs -n $NAMESPACE -l app.kubernetes.io/instance=${MC_RELEASE_NAME},app.kubernetes.io/component=temporal-postgresql"
            mc_ringpop_hint
            exit 1
        fi
        if [ "$((MC_VERIFY_ELAPSED - reported))" -ge 30 ]; then
            reported=$MC_VERIFY_ELAPSED
            printf "    ${BLUE}[...]${NC} Schema Jobs still running:%s%s (%ss elapsed)\n" "$pending" "$unread" "$MC_VERIFY_ELAPSED"
        fi
        sleep 5
    done
    printf "    ${GREEN}[OK]${NC} MC database schema ready\n"
}

# Waits, within what is left of MC_VERIFY_TIMEOUT, for the MC agent Deployment's
# current generation to have every replica updated and available. Polls the status
# rather than `kubectl rollout status`, which fails at once on ProgressDeadlineExceeded:
# a Deployment created when the chart was applied can pass its progress deadline while
# the schema Jobs still run.
wait_mc_agent_rollout() {
    local deploy="${MC_RELEASE_NAME}-agent" out gen obs want upd avail reported
    reported=$MC_VERIFY_ELAPSED
    printf "    ${BLUE}[...]${NC} Waiting for MC agent deployment (%ss of %ss left)\n" \
        "$((MC_VERIFY_TIMEOUT - MC_VERIFY_ELAPSED))" "$MC_VERIFY_TIMEOUT"
    while :; do
        out=$(kubectl get deployment "$deploy" -n "$NAMESPACE" --request-timeout=10s \
            -o jsonpath='{.metadata.generation} {.status.observedGeneration} {.spec.replicas} {.status.updatedReplicas} {.status.availableReplicas}' 2>/dev/null) || out=""
        read -r gen obs want upd avail <<EOF
$out
EOF
        if [ -n "$gen" ] && [ "${obs:-0}" -ge "$gen" ] && [ "${upd:-0}" -ge "${want:-1}" ] && [ "${avail:-0}" -ge "${want:-1}" ]; then
            return 0
        fi
        mc_verify_tick
        [ "$MC_VERIFY_ELAPSED" -lt "$MC_VERIFY_TIMEOUT" ] || return 1
        if [ "$((MC_VERIFY_ELAPSED - reported))" -ge 30 ]; then
            reported=$MC_VERIFY_ELAPSED
            printf "    ${BLUE}[...]${NC} MC agent not ready yet: %s/%s available (%ss elapsed)\n" "${avail:-0}" "${want:-1}" "$MC_VERIFY_ELAPSED"
        fi
        sleep 5
    done
}

verify_mc_installation() {
    local selector="app.kubernetes.io/instance=${MC_RELEASE_NAME},app.kubernetes.io/component=agent"
    local status=0 pod="" health="" attempt chart
    echo ""
    MC_VERIFY_START=$(date +%s)
    MC_VERIFY_ELAPSED=0
    wait_mc_schema_jobs
    if ! wait_mc_agent_rollout; then
        printf "    ${RED}[FAIL]${NC} MC agent deployment did not become ready in %ss\n" "$MC_VERIFY_TIMEOUT"
        log_error "MC agent pod failed to start. Debug with:"
        echo "  kubectl describe pod -n $NAMESPACE -l $selector"
        echo "  kubectl logs -n $NAMESPACE -l $selector"
        echo "  kubectl get deployment ${MC_RELEASE_NAME}-agent -n $NAMESPACE -o yaml"
        mc_ringpop_hint
        exit 1
    fi
    printf "    ${GREEN}[OK]${NC} MC agent deployment ready\n"
    chart=$(kubectl get deployment "${MC_RELEASE_NAME}-agent" -n "$NAMESPACE" --request-timeout=10s \
        -o jsonpath='{.metadata.labels.helm\.sh/chart}' 2>/dev/null) || chart=""
    chart=${chart#mc-}
    if [ -n "$chart" ] && [ "${MC_CHART_SOURCE:-}" != "local" ]; then
        if [ -n "${MC_CHART_VERSION:-}" ] && [ "$chart" != "$MC_CHART_VERSION" ]; then
            log_info "The MC upgraded itself to chart ${chart} during install (installed ${MC_CHART_VERSION})"
        else
            log_info "MC chart: ${chart}"
        fi
    fi

    for attempt in $(seq 1 12); do
        pod=$(kubectl get pods -n "$NAMESPACE" -l "$selector" \
            -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
        if [ -n "$pod" ]; then
            health=$(kubectl exec -n "$NAMESPACE" "$pod" -- curl -sf http://localhost:8080/health 2>/dev/null || true)
            if printf '%s\n' "$health" | grep -qi "ok"; then
                break
            fi
        fi
        health=""
        printf "\r    ${BLUE}[...]${NC} MC health check... (attempt %d/12)        " "$attempt"
        sleep 5
    done
    if [ -z "$health" ]; then
        printf "\r    ${RED}[FAIL]${NC} MC health check failed after 12 attempts\n"
        log_error "The MC agent is running but not healthy. Debug with:"
        echo "  kubectl logs -n $NAMESPACE ${pod:-<mc agent pod>}"
        exit 1
    fi
    printf "\r    ${GREEN}[OK]${NC} MC health check passed                    \n"

    status=0
    kubectl rollout status "deployment/${MC_RELEASE_NAME}-worker" -n "$NAMESPACE" --timeout=300s >/dev/null 2>&1 &
    spin_wait "$!" "Waiting for MC worker deployment..." || status=$?
    if [ "$status" -eq 0 ]; then
        printf "\r    ${GREEN}[OK]${NC} MC worker deployment ready         \n"
    else
        printf "\r    ${YELLOW}[WARN]${NC} MC worker deployment taking longer than expected\n"
        mc_ringpop_hint
    fi

    echo ""
    log_info "MC pod status:"
    kubectl get pods -n "$NAMESPACE" -l "app.kubernetes.io/instance=${MC_RELEASE_NAME}" -o wide 2>/dev/null | sed 's/^/    /'
}

# =============================================================================
# Main
# =============================================================================

main_local() {
    show_banner
    printf "${CYAN}════════════════════════════════════════════════════════════════════${NC}\n"
    printf "${CYAN}                     LOCAL MODE INSTALLATION                        ${NC}\n"
    printf "${CYAN}════════════════════════════════════════════════════════════════════${NC}\n"
    echo ""

    local use_custom_endpoints=false
    if [ -n "$CUSTOM_GRPC_ENDPOINT" ]; then
        use_custom_endpoints=true
        log_info "Using custom gRPC endpoint: $CUSTOM_GRPC_ENDPOINT"
        if [ -n "$CUSTOM_API_ENDPOINT" ]; then
            log_info "Using custom API endpoint: $CUSTOM_API_ENDPOINT"
        fi
        echo ""
    fi

    local total_steps=8
    if [ "$use_custom_endpoints" = "true" ]; then
        total_steps=7  # Skip mock cloud step
    fi

    local step=1

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Checking local prerequisites"
    check_local_prerequisites
    step=$((step + 1))

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Setting up k3d cluster"
    create_k3d_cluster
    step=$((step + 1))

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Building Docker images"
    build_local_images
    step=$((step + 1))

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Creating Kubernetes namespace"
    create_namespace
    step=$((step + 1))

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Starting Temporal"
    start_temporal
    step=$((step + 1))

    if [ "$use_custom_endpoints" = "false" ]; then
        echo ""
        printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
        log_step "Starting Mock Cloud gRPC server"
        start_mock_cloud
        step=$((step + 1))
    fi

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Setting up credentials"
    fetch_credentials_local
    create_registry_secret
    create_cloud_credentials_secret
    create_oauth_credentials_secret
    create_local_secrets
    step=$((step + 1))

    echo ""
    printf "${CYAN}Step ${step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Installing Klyro Edge"
    install_helm_chart_local

    echo ""
    printf "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
    log_step "Verifying installation"
    verify_local_installation
    verify_rbac

    if [ "$use_custom_endpoints" = "false" ]; then
        echo ""
        printf "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
        run_connectivity_tests
    fi

    echo ""
    echo ""
    printf "${GREEN}╔═══════════════════════════════════════════════════════════════════╗${NC}\n"
    printf "${GREEN}║${NC}                                                                   ${GREEN}║${NC}\n"
    printf "${GREEN}║${NC}   ${GREEN}✓ Klyro Edge LOCAL installation complete!${NC}                     ${GREEN}║${NC}\n"
    printf "${GREEN}║${NC}                                                                   ${GREEN}║${NC}\n"
    printf "${GREEN}╚═══════════════════════════════════════════════════════════════════╝${NC}\n"
    echo ""
    echo "  Agent ID:      ${GREEN}$AGENT_ID${NC}"
    echo "  Namespace:     ${GREEN}$NAMESPACE${NC}"
    echo "  Release:       ${GREEN}$RELEASE_NAME${NC}"
    echo "  Mode:          ${CYAN}LOCAL${NC}"
    if [ "$use_custom_endpoints" = "true" ]; then
        echo "  gRPC Endpoint: ${CYAN}$CUSTOM_GRPC_ENDPOINT${NC}"
        [ -n "$CUSTOM_API_ENDPOINT" ] && echo "  API Endpoint:  ${CYAN}$CUSTOM_API_ENDPOINT${NC}"
    fi
    echo ""
    printf "${BLUE}Components running:${NC}\n"
    if [ "$use_custom_endpoints" = "true" ]; then
        echo "  - Agent:       Connected to custom cloud endpoints"
    else
        echo "  - Agent:       Connected to mock cloud & Temporal"
        echo "  - Mock Cloud:  gRPC server for agent registration"
    fi
    echo "  - Worker:      Polling Temporal for tasks"
    echo "  - Temporal:    Workflow orchestration"
    echo ""
    printf "${BLUE}Useful commands:${NC}\n"
    echo "  kubectl get pods -n $NAMESPACE"
    echo "  kubectl logs -n $NAMESPACE -l app.kubernetes.io/component=agent -f"
    if [ "$use_custom_endpoints" = "false" ]; then
        echo "  kubectl logs -n $NAMESPACE -l app=mock-cloud -f"
    fi
    echo "  kubectl port-forward -n $NAMESPACE svc/temporal-web 8088:8088"
    echo ""
    printf "${BLUE}To clean up:${NC}\n"
    echo "  k3d cluster delete klyro-local"
    echo ""
}

main_production() {
    show_banner

    INSTALL_TOKEN="$1"

    if [ -z "$INSTALL_TOKEN" ]; then
        log_error "Missing install token"
        echo ""
        usage
        exit 1
    fi

    case "$INSTALL_TOKEN" in
        inst_*)
            ;;
        *)
            log_warn "Token format looks unusual (expected: inst_xxxx...)"
            ;;
    esac

    resolve_product
    resolve_cli_install
    if product_has mc; then
        resolve_mc_database
    fi

    STEP_TOTAL=5
    product_has researcher && STEP_TOTAL=$((STEP_TOTAL + 2))
    product_has mc && STEP_TOTAL=$((STEP_TOTAL + 1))
    [ "$MC_DB_MODE" = "external" ] && STEP_TOTAL=$((STEP_TOTAL + 1))
    [ -z "$CLI_USER" ] || STEP_TOTAL=$((STEP_TOTAL + 1))
    STEP_CURRENT=1

    begin_step "Checking prerequisites"
    check_cli
    prep_cli_host
    check_prerequisites
    resolve_egress
    if product_has mc; then
        resolve_mc_scim
        resolve_mc_credential_store
    fi

    if [ "$MC_DB_MODE" = "external" ]; then
        begin_step "Checking the MC database"
        validate_mc_external_database
    fi

    begin_step "Cleaning up existing installation"
    if product_has researcher; then
        cleanup_existing_installation
    fi
    if product_has mc; then
        cleanup_existing_mc_installation
    fi

    begin_step "Fetching credentials"
    if product_has mc; then
        fetch_mc_credentials
    fi
    if product_has researcher; then
        fetch_credentials "$INSTALL_TOKEN"
    fi

    begin_step "Creating Kubernetes resources"
    create_namespace
    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        create_extra_ca_configmap kube-system
    else
        create_extra_ca_configmap
    fi
    create_egress_proxy_secret
    if product_has researcher; then
        create_registry_secret
        create_cloud_credentials_secret
        create_oauth_credentials_secret
        create_anthropic_secret
        create_openai_secret

        # Store agent metadata for --reinstall recovery
        kubectl create configmap klyro-agent-info \
            --from-literal=agent-id="$AGENT_ID" \
            --from-literal=tenant-id="$TENANT_ID" \
            --from-literal=site-id="$SITE_ID" \
            --from-literal=grpc-endpoint="$GRPC_ENDPOINT" \
            --from-literal=auth-endpoint="${AUTH_ENDPOINT:-}" \
            --from-literal=proxy="${PROXY_URL:+true}" \
            --from-literal=no-proxy="${NO_PROXY_EXTRA:-}" \
            --from-literal=extra-ca="${CA_FILE:+true}" \
            --from-literal=chart-repo="${CHART_REPO:-}" \
            --namespace="$NAMESPACE" \
            --dry-run=client -o yaml | kubectl apply -f - >/dev/null
        printf "    ${GREEN}[OK]${NC} ConfigMap: klyro-agent-info (for reinstall recovery)\n"
    fi
    if product_has mc; then
        create_mc_secrets
    fi

    if product_has researcher; then
        begin_step "Starting Temporal"
        start_temporal

        begin_step "Installing Helm chart"
        install_helm_chart
        record_rollout_baselines
    fi

    if product_has mc; then
        begin_step "Installing the MC Helm chart"
        install_mc_chart
        restart_mc_for_new_credentials
    fi

    begin_step "Verifying installation"
    if product_has researcher; then
        verify_installation
        verify_rbac
    fi
    if product_has mc; then
        verify_mc_installation
        verify_rbac "$MC_RELEASE_NAME" "$MC_RELEASE_NAME"
        verify_mc_scim_ingress
    fi

    if [ -n "$CLI_USER" ]; then
        begin_step "Installing the klyro CLI for $CLI_USER"
        install_cli
    fi

    echo ""
    echo ""
    printf "${GREEN}╔═══════════════════════════════════════════════════════════════════╗${NC}\n"
    printf "${GREEN}║${NC}                                                                   ${GREEN}║${NC}\n"
    printf "${GREEN}║${NC}   ${GREEN}✓ Klyro Edge installed successfully!${NC}                          ${GREEN}║${NC}\n"
    printf "${GREEN}║${NC}                                                                   ${GREEN}║${NC}\n"
    printf "${GREEN}╚═══════════════════════════════════════════════════════════════════╝${NC}\n"
    echo ""
    if product_has researcher; then
        echo "  Agent ID:   ${GREEN}$AGENT_ID${NC}"
        echo "  Namespace:  ${GREEN}$NAMESPACE${NC}"
        echo "  Release:    ${GREEN}$RELEASE_NAME${NC}"
        echo ""
    fi
    if product_has mc; then
        echo "  MC Agent ID:   ${GREEN}$MC_AGENT_ID${NC}"
        echo "  MC Namespace:  ${GREEN}$NAMESPACE${NC}"
        echo "  MC Release:    ${GREEN}$MC_RELEASE_NAME${NC}"
        echo "  MC Database:   ${GREEN}$MC_DB_MODE${NC}"
        if [ -n "$MC_SCIM_HOST" ]; then
            echo "  MC SCIM:       ${GREEN}https://$MC_SCIM_HOST/api/v1/applications/<app_external_id>/<pipeline_external_id>/scim/v2${NC}"
            if [ -z "$MC_SCIM_TLS_SECRET" ]; then
                echo "                 ${YELLOW}no trusted TLS: the ingress controller's default certificate (self-signed on k3s); re-run with --scim-tls-cert/--scim-tls-key${NC}"
            fi
            if [ -n "$SCIM_FIREWALL_FIX" ]; then
                echo "                 ${YELLOW}blocked by this node's firewalld (443/tcp); to open it, run: ${SCIM_FIREWALL_FIX}${NC}"
            fi
        elif [ "$MC_SCIM_STATE" = "off" ]; then
            echo "  MC SCIM:       off (--no-scim-ingress); the IGA reaches it through Klyro Cloud"
        else
            echo "  MC SCIM:       through the Klyro relay; for direct ingress, re-run with --scim-host <dns name your IGA reaches>"
        fi
        if [ "$MC_CREDENTIAL_STORE" = "on" ]; then
            echo "  MC Credentials: ${GREEN}Secret ${MC_RELEASE_NAME}-credentials${NC}; squad token: Secret ${MC_RELEASE_NAME}-squad-token (charts/mc/README.md, Squad access)"
        else
            echo "  MC Credentials: off (--no-credential-store); re-run with --credential-store to turn it on"
        fi
        echo ""
    fi
    print_cli_summary
    print_host_prep_summary
    if [ -n "$POD_FIREWALL_FIX" ]; then
        echo "  ${YELLOW}Host firewall: firewalld does not trust the pod and service networks; as root, run: ${POD_FIREWALL_FIX}${NC}"
        echo ""
    fi
    printf "${BLUE}Useful commands:${NC}\n"
    echo "  kubectl get pods -n $NAMESPACE"
    if product_has researcher; then
        echo "  kubectl logs -n $NAMESPACE -l app.kubernetes.io/component=agent -f"
        echo "  helm status $RELEASE_NAME -n $NAMESPACE"
    fi
    if product_has mc; then
        echo "  kubectl logs -n $NAMESPACE -l app.kubernetes.io/instance=$MC_RELEASE_NAME,app.kubernetes.io/component=worker -f"
        echo "  helm status $MC_RELEASE_NAME -n $NAMESPACE"
    fi
    echo ""
}

# =============================================================================
# Reinstall Mode — reuses existing agent credentials from K8s secrets
# =============================================================================

recover_credentials_from_secrets() {
    log_info "Recovering agent credentials from existing K8s secrets..."

    AGENT_ID=$(kubectl get secret klyro-cloud-credentials -n "$NAMESPACE" \
        -o jsonpath='{.data.agent-id}' 2>/dev/null | base64 -d 2>/dev/null)
    ACCESS_TOKEN=$(kubectl get secret klyro-cloud-credentials -n "$NAMESPACE" \
        -o jsonpath='{.data.access-token}' 2>/dev/null | base64 -d 2>/dev/null)
    OAUTH2_CLIENT_ID=$(kubectl get secret klyro-edge-oauth-credentials -n "$NAMESPACE" \
        -o jsonpath='{.data.client-id}' 2>/dev/null | base64 -d 2>/dev/null)
    OAUTH2_CLIENT_SECRET=$(kubectl get secret klyro-edge-oauth-credentials -n "$NAMESPACE" \
        -o jsonpath='{.data.client-secret}' 2>/dev/null | base64 -d 2>/dev/null)

    # Recover tenant/site/endpoints from agent-info configmap
    TENANT_ID=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
        -o jsonpath='{.data.tenant-id}' 2>/dev/null || echo "")
    SITE_ID=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
        -o jsonpath='{.data.site-id}' 2>/dev/null || echo "")
    GRPC_ENDPOINT=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
        -o jsonpath='{.data.grpc-endpoint}' 2>/dev/null || echo "grpc.klyro.security:443")
    AUTH_ENDPOINT=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
        -o jsonpath='{.data.auth-endpoint}' 2>/dev/null || echo "")

    # Egress settings of the original install; a flag passed on this run wins.
    if [ -z "$PROXY_URL" ]; then
        PROXY_URL=$(kubectl get secret "$EGRESS_PROXY_SECRET" -n "$NAMESPACE" \
            -o jsonpath='{.data.proxy-url}' 2>/dev/null | base64 -d 2>/dev/null || echo "")
        if [ -z "$PROXY_URL" ] && [ "$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
            -o jsonpath='{.data.proxy}' 2>/dev/null)" = "true" ]; then
            log_error "The original install used --proxy, but Secret $EGRESS_PROXY_SECRET is missing or unreadable"
            echo "  Pass --proxy again, or restore the Secret, before --reinstall."
            exit 1
        fi
    fi
    if [ -z "$NO_PROXY_EXTRA" ]; then
        NO_PROXY_EXTRA=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
            -o jsonpath='{.data.no-proxy}' 2>/dev/null || echo "")
    fi
    detect_env_proxy
    if [ -z "$CA_FILE" ]; then
        EXTRA_CA_RECOVERED=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
            -o jsonpath='{.data.extra-ca}' 2>/dev/null || echo "")
    fi
    if [ -z "$CHART_REPO" ]; then
        CHART_REPO=$(kubectl get configmap klyro-agent-info -n "$NAMESPACE" \
            -o jsonpath='{.data.chart-repo}' 2>/dev/null || echo "")
    fi

    GHCR_TOKEN=$(kubectl get secret ghcr-credentials -n "$NAMESPACE" \
        -o jsonpath='{.data.token}' 2>/dev/null | base64 -d 2>/dev/null)

    if [ -z "$AGENT_ID" ] || [ -z "$OAUTH2_CLIENT_ID" ] || [ -z "$OAUTH2_CLIENT_SECRET" ]; then
        log_error "Could not recover credentials from existing secrets"
        echo ""
        echo "Required secrets not found in namespace $NAMESPACE."
        echo "Please use a fresh install token instead:"
        echo "  curl -sfL https://get.klyro.security | sh -s -- <NEW_TOKEN>"
        exit 1
    fi

    log_success "Recovered agent credentials"
    echo ""
    echo "    ┌─────────────────────────────────────────────────────┐"
    echo "    │  Agent ID:  $AGENT_ID"
    echo "    │  Mode:      reinstall (reusing existing credentials)"
    echo "    └─────────────────────────────────────────────────────┘"
}

main_reinstall() {
    show_banner
    printf "${YELLOW}════════════════════════════════════════════════════════════════════${NC}\n"
    printf "${YELLOW}                     REINSTALL MODE                                 ${NC}\n"
    printf "${YELLOW}════════════════════════════════════════════════════════════════════${NC}\n"
    echo ""

    local total_steps=5
    local current_step=1

    printf "${BLUE}Step ${current_step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Checking prerequisites"
    check_prerequisites
    current_step=$((current_step + 1))

    echo ""
    printf "${BLUE}Step ${current_step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Recovering credentials from existing secrets"
    recover_credentials_from_secrets
    validate_egress_settings
    resolve_egress
    current_step=$((current_step + 1))

    # Re-create secrets that may have been lost (anthropic, openai)
    echo ""
    printf "${BLUE}Step ${current_step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Refreshing secrets"
    create_anthropic_secret
    create_openai_secret
    if [ "$USE_HELM_CONTROLLER" = "true" ]; then
        create_extra_ca_configmap kube-system
    else
        create_extra_ca_configmap
    fi
    create_egress_proxy_secret
    # Keep the egress settings of this run for the next --reinstall.
    local extra_ca_flag=""
    extra_ca_enabled && extra_ca_flag="true"
    kubectl patch configmap klyro-agent-info -n "$NAMESPACE" --type merge -p \
        "{\"data\":{\"proxy-url\":null,\"proxy\":\"${PROXY_URL:+true}\",\"no-proxy\":\"${NO_PROXY_EXTRA}\",\"extra-ca\":\"${extra_ca_flag}\",\"chart-repo\":\"${CHART_REPO}\"}}" \
        >/dev/null 2>&1 || {
        log_error "Could not save the egress settings in ConfigMap klyro-agent-info"
        exit 1
    }
    current_step=$((current_step + 1))

    echo ""
    printf "${BLUE}Step ${current_step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Upgrading Helm chart"
    GRPC_ENDPOINT="${GRPC_ENDPOINT:-grpc.klyro.security:443}"
    AUTH_ENDPOINT="${AUTH_ENDPOINT:-https://keycloak.prod.klyro.security/realms/klyro}"
    CHART_VERSION=""  # Use latest
    install_helm_chart
    record_rollout_baselines
    current_step=$((current_step + 1))

    echo ""
    printf "${BLUE}Step ${current_step}/${total_steps}${NC} ─────────────────────────────────────────────────────────\n"
    log_step "Verifying installation"
    verify_installation
    verify_rbac

    echo ""
    echo ""
    printf "${GREEN}╔═══════════════════════════════════════════════════════════════════╗${NC}\n"
    printf "${GREEN}║${NC}                                                                   ${GREEN}║${NC}\n"
    printf "${GREEN}║${NC}   ${GREEN}✓ Klyro Edge reinstalled successfully!${NC}                        ${GREEN}║${NC}\n"
    printf "${GREEN}║${NC}                                                                   ${GREEN}║${NC}\n"
    printf "${GREEN}╚═══════════════════════════════════════════════════════════════════╝${NC}\n"
    echo ""
    echo "  Agent ID:   ${GREEN}$AGENT_ID${NC}"
    echo "  Namespace:  ${GREEN}$NAMESPACE${NC}"
    echo "  Mode:       ${YELLOW}REINSTALL${NC} (reused existing credentials)"
    echo ""
}

# =============================================================================
# Environment URL Defaults
# =============================================================================

# The telemetry ingest host for an environment name or a gRPC endpoint of that environment.
otel_ingest_host_for_env() {
    case "$1" in
        dev|*dev.*) echo "otel-ingest.dev.klyro.security" ;;
        staging|*staging.*) echo "otel-ingest.staging.klyro.security" ;;
        *) echo "otel-ingest.klyro.security" ;;
    esac
}

apply_env_defaults() {
    case "$KLYRO_ENV" in
        dev)
            KLYRO_API_URL="${KLYRO_API_URL:-https://api.dev.klyro.security}"
            GRPC_ENDPOINT="grpc.dev.klyro.security:443"
            AUTH_ENDPOINT="${AUTH_ENDPOINT:-https://keycloak.dev.klyro.security/realms/klyro}"
            KLYRO_REGISTRY="registry.dev.klyro.security"
            KLYRO_CDN="cdn.dev.klyro.security"
            LLM_GATEWAY_URL="https://llm.dev.klyro.security"
            ;;
        staging)
            KLYRO_API_URL="${KLYRO_API_URL:-https://api.staging.klyro.security}"
            GRPC_ENDPOINT="grpc.staging.klyro.security:443"
            AUTH_ENDPOINT="${AUTH_ENDPOINT:-https://keycloak.staging.klyro.security/realms/klyro}"
            KLYRO_REGISTRY="registry.staging.klyro.security"
            KLYRO_CDN="cdn.staging.klyro.security"
            LLM_GATEWAY_URL="https://llm.staging.klyro.security"
            ;;
        production|"")
            KLYRO_API_URL="${KLYRO_API_URL:-https://api.klyro.security}"
            GRPC_ENDPOINT="grpc.klyro.security:443"
            AUTH_ENDPOINT="${AUTH_ENDPOINT:-https://keycloak.prod.klyro.security/realms/klyro}"
            KLYRO_REGISTRY="registry.klyro.security"
            KLYRO_CDN="cdn.klyro.security"
            LLM_GATEWAY_URL="https://llm.klyro.security"
            ;;
        *)
            log_error "Unknown environment: $KLYRO_ENV. Valid values: dev, staging, production"
            exit 1
            ;;
    esac
    # Image ref prefix routed through the registry.<env>.klyro.security pull-through
    # cache (zot). Empty in --local mode (images pulled from their upstream directly).
    if [ "$is_local" = "true" ]; then
        REGISTRY_PREFIX=""
    else
        REGISTRY_PREFIX="${KLYRO_REGISTRY}/"
    fi
}

# ---- preflight ----

PF_US=$(printf '\037')
PF_LINES=""
PF_SECTIONS=""
PF_SECTION=""
PF_N_PASS=0
PF_N_WARN=0
PF_N_FAIL=0
PF_PARTIAL=false
PF_DEADLINE=0
PF_BUDGET_S=0
PF_TIME_CAPPED=false
PF_MAX_TIME=15
PF_IMAGE_MAX_TIME=45
PF_IMAGE_BUDGET_S=90
PF_PRODUCT_RESERVE_S=20
PF_LOG=""
PF_OS_RELEASE="/etc/os-release"
PF_MEMINFO="/proc/meminfo"
PF_SELINUX_DIR="/usr/share/selinux"
PF_CLUSTER_UP=false
PF_SUPPORTED_OS="RHEL/Rocky/Alma 8-9, Ubuntu 20.04-24.04, Debian 11-12 or Amazon Linux 2023"

pf_section() {
    PF_SECTION="$1"
    PF_SECTIONS="${PF_SECTIONS}${1}
"
}

pf_rec() {
    case "$1" in
        PASS) PF_N_PASS=$((PF_N_PASS + 1)) ;;
        WARN) PF_N_WARN=$((PF_N_WARN + 1)) ;;
        FAIL) PF_N_FAIL=$((PF_N_FAIL + 1)) ;;
    esac
    PF_LINES="${PF_LINES}${PF_SECTION}${PF_US}${1}${PF_US}${2}${PF_US}${3}${PF_US}${4:-}
"
}

# Succeeds while the time budget lasts; once it is spent, marks the run partial and
# records the time-cap line (once).
pf_budget_ok() {
    [ "$(date +%s)" -lt "$PF_DEADLINE" ] && return 0
    PF_PARTIAL=true
    if [ "$PF_TIME_CAPPED" != true ]; then
        PF_TIME_CAPPED=true
        pf_rec WARN "Time cap" "stopped after ${PF_BUDGET_S}s, before every check ran" \
            "rerun --preflight; if it stops again, send this partial report"
    fi
    return 1
}

pf_redact_url() {
    printf '%s' "$1" | sed 's#^\([A-Za-z][A-Za-z0-9+.-]*://\)\{0,1\}[^@/]*@#\1***@#'
}

pf_installer_version() {
    local sum
    if [ -f "$0" ] && [ -r "$0" ]; then
        sum=$( { sha256sum "$0" 2>/dev/null || shasum -a 256 "$0" 2>/dev/null; } | cut -c1-12)
        [ -n "$sum" ] && { echo "sha256:$sum"; return 0; }
    fi
    echo "unknown (piped)"
}

# The value of variable $1 in PF_OS_RELEASE.
pf_os_field() {
    # shellcheck source=/dev/null
    ( . "$PF_OS_RELEASE" 2>/dev/null; eval "printf '%s\\n' \"\${$1:-}\"" )
}

pf_os() {
    local name
    if [ -r "$PF_OS_RELEASE" ]; then
        name=$(pf_os_field PRETTY_NAME)
        [ -n "$name" ] && { echo "$name"; return 0; }
    fi
    uname -sr 2>/dev/null || echo unknown
}

pf_result_line() {
    local verdict=READY note=""
    if [ "$PF_N_FAIL" -gt 0 ] || [ "$PF_PARTIAL" = true ]; then
        verdict="NOT READY"
    fi
    [ "$PF_PARTIAL" = true ] && note=" - partial: the run stopped before every check ran"
    echo "Result: $verdict ($PF_N_FAIL fail, $PF_N_WARN warn, $PF_N_PASS pass)$note"
}

pf_render() {
    local title section status name detail fix env_proxy
    env_proxy=$(pf_env_proxy)
    echo "===== BEGIN KLYRO PREFLIGHT REPORT ====="
    echo "Installer: $(pf_installer_version)"
    echo "Environment: ${KLYRO_ENV:-production}"
    echo "Product: ${PRODUCT_LABEL:-researcher,mc,cli (default)}"
    if [ "$PRODUCT" = none ]; then
        echo "Mode: klyro CLI only (no cluster)"
    elif [ "$bootstrap_cluster" = true ] && pf_k3s_will_install; then
        echo "Mode: --bootstrap (installs k3s)"
    elif [ "$bootstrap_cluster" = true ] && [ "${PF_CLUSTER_UP:-}" = true ]; then
        echo "Mode: --bootstrap (reuses the existing cluster)"
    elif [ "$bootstrap_cluster" = true ]; then
        echo "Mode: --bootstrap (reuses the existing k3s)"
    else
        echo "Mode: existing cluster"
    fi
    echo "Host: $(uname -n 2>/dev/null || echo unknown) / $(pf_os) / $(uname -m 2>/dev/null || echo unknown)"
    echo "Run as: $(id -un 2>/dev/null || echo unknown) (uid $(id -u 2>/dev/null || echo unknown))"
    echo "Proxy: --proxy $(pf_redact_url "${PROXY_URL:-none}")${PROXY_AUTO:+ (auto-detected from HTTPS_PROXY)}, shell HTTPS_PROXY $(pf_redact_url "${env_proxy:-none}")"
    echo "Time: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
    pf_result_line
    while IFS= read -r title; do
        [ -n "$title" ] || continue
        echo ""
        echo "== $title =="
        while IFS="$PF_US" read -r section status name detail fix; do
            [ "$section" = "$title" ] || continue
            if [ "$status" = OUT ]; then
                echo "    $detail"
                continue
            fi
            echo "[$status] $name: $detail"
            [ -n "$fix" ] && echo "    -> fix: $fix"
        done <<PF_EOF
$PF_LINES
PF_EOF
    done <<PF_EOF
$PF_SECTIONS
PF_EOF
    echo ""
    pf_result_line
    echo "===== END KLYRO PREFLIGHT REPORT ====="
    echo "Send everything between the markers to Klyro. When it says READY, rerun without --preflight."
}

# Writes report $1 to a new file, mode 600, in the current directory, else $TMPDIR: never
# to a file or link that already exists. Sets PF_LOG to it, or empty when none was written.
pf_write_log() {
    local name dir f
    name="klyro-preflight-$(uname -n 2>/dev/null || echo host)-$(date -u '+%Y%m%dT%H%M%SZ')"
    PF_LOG=""
    for dir in . ${TMPDIR:+"$TMPDIR"}; do
        for f in "$dir/$name.log" "$dir/$name-$$.log"; do
            [ ! -e "$f" ] && [ ! -L "$f" ] || continue
            if ( umask 077; set -C; printf '%s\n' "$1" > "$f" ) 2>/dev/null; then
                PF_LOG="$f"
                return 0
            fi
        done
    done
}

pf_report() {
    local out
    out=$(pf_render)
    pf_write_log "$out"
    [ -z "$PF_LOG" ] || echo "Report saved to $PF_LOG"
    printf '%s\n' "$out"
}

pf_finish() {
    if [ "$PF_N_FAIL" -gt 0 ] || [ "$PF_PARTIAL" = true ]; then
        exit 1
    fi
    exit 0
}

pf_interrupted() {
    trap - INT
    PF_PARTIAL=true
    pf_rec WARN "Interrupted" "the run was stopped before every check ran" "rerun --preflight and let it finish (it takes at most a few minutes)"
    pf_report
    exit 1
}

pf_check_token() {
    case "$INSTALL_TOKEN" in
        "") pf_rec INFO "Install token" "not given (not needed for preflight)" ;;
        inst_*) pf_rec PASS "Install token" "format ok (not redeemed)" ;;
        *) pf_rec WARN "Install token" "format looks unusual (expected inst_...)" \
            "copy the install command from https://app.klyro.security, Agents, Add Agent" ;;
    esac
}

# Records the line for the evaluator that just ran: ok PASS, warn WARN, fail FAIL, and
# skip INFO, or with $2 = root the not-verified WARN of a probe that needs root.
pf_ev_rec() {
    case "$EV_STATUS" in
        ok) pf_rec PASS "$1" "$EV_DETAIL" ;;
        warn) pf_rec WARN "$1" "$EV_DETAIL" "$EV_FIX" ;;
        fail) pf_rec FAIL "$1" "$EV_DETAIL" "$EV_FIX" ;;
        *)
            if [ "${2:-}" = "root" ]; then
                pf_rec WARN "$1" "not verified (needs root)" "run the preflight as root or with sudo"
            else
                pf_rec INFO "$1" "$EV_DETAIL"
            fi
            ;;
    esac
}

pf_check_os() {
    local kernel arch id ver pretty
    kernel=$(uname -s 2>/dev/null || echo unknown)
    arch=$(uname -m 2>/dev/null || echo unknown)
    if [ "$kernel" != "Linux" ]; then
        pf_rec FAIL OS "$kernel is not Linux" "run the installer on a Linux host: $PF_SUPPORTED_OS"
        return 0
    fi
    case "$arch" in
        x86_64|aarch64) ;;
        *)
            pf_rec FAIL OS "unsupported architecture $arch" "use an x86_64 or aarch64 host"
            return 0
            ;;
    esac
    id="" ver="" pretty=""
    if [ -r "$PF_OS_RELEASE" ]; then
        id=$(pf_os_field ID)
        ver=$(pf_os_field VERSION_ID)
        pretty=$(pf_os_field PRETTY_NAME)
    fi
    [ -n "$pretty" ] || pretty="${id:-unknown Linux}${ver:+ $ver}"
    case "$id:$ver" in
        rhel:8|rhel:8.*|rhel:9|rhel:9.*|rocky:8|rocky:8.*|rocky:9|rocky:9.*|almalinux:8|almalinux:8.*|almalinux:9|almalinux:9.*|\
        ubuntu:20.04|ubuntu:20.10|ubuntu:21.04|ubuntu:21.10|ubuntu:22.04|ubuntu:22.10|ubuntu:23.04|ubuntu:23.10|ubuntu:24.04|\
        debian:11|debian:11.*|debian:12|debian:12.*|amzn:2023|amzn:2023.*)
            pf_rec PASS OS "$pretty ($arch)"
            ;;
        *)
            pf_rec WARN OS "untested distro $pretty ($arch)" "the install may still work; tested: $PF_SUPPORTED_OS"
            ;;
    esac
}

# The MemTotal, in kB, that counts as $1 GiB: 90% of it, since the kernel and firmware keep
# part of the RAM (a 16 GiB instance shows about 15.1 GiB, reported as 16 GiB).
pf_mem_floor_kb() {
    echo $(( $1 * 1048576 * 9 / 10 ))
}

pf_check_cpu_mem() {
    local n kb gib
    n=$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || true)
    case "$n" in
        ''|*[!0-9]*) pf_rec WARN CPU "could not read the CPU count" "check that nproc works on this host" ;;
        *)
            if [ "$n" -lt 2 ]; then
                pf_rec FAIL CPU "$n cores, at least 2 required" "give the host at least 4 vCPUs (2 minimum)"
            elif [ "$n" -lt 4 ]; then
                pf_rec WARN CPU "$n cores, 4 recommended" "give the host at least 4 vCPUs"
            else
                pf_rec PASS CPU "$n cores"
            fi
            ;;
    esac
    kb=$(awk '/^MemTotal:/ {print $2; exit}' "$PF_MEMINFO" 2>/dev/null || true)
    case "$kb" in
        ''|*[!0-9]*) pf_rec WARN Memory "could not read MemTotal from $PF_MEMINFO" "check the host has at least 16 GiB of RAM" ;;
        *)
            gib=$(( (kb + 1048575) / 1048576 ))
            [ "$kb" -ge "$(pf_mem_floor_kb "$gib")" ] || gib=$(( (kb + 524288) / 1048576 ))
            if [ "$kb" -lt "$(pf_mem_floor_kb 8)" ]; then
                pf_rec FAIL Memory "$gib GiB, at least 8 GiB required" "give the host at least 16 GiB of RAM (8 GiB minimum)"
            elif [ "$kb" -lt "$(pf_mem_floor_kb 16)" ]; then
                pf_rec WARN Memory "$gib GiB, 16 GiB recommended" "give the host at least 16 GiB of RAM"
            else
                pf_rec PASS Memory "$gib GiB"
            fi
            ;;
    esac
}

# Prints fapolicyd's permissive setting from $FAPOLICYD_CONF, read as root and never
# changed: 1 (it logs denials and blocks nothing), 0 (it enforces; also fapolicyd's default
# when the file or the setting is absent), or nothing when the file exists but cannot be read.
pf_fapolicyd_permissive() {
    local conf
    if ! conf=$(as_root cat "$FAPOLICYD_CONF" 2>/dev/null); then
        as_root test -e "$FAPOLICYD_CONF" 2>/dev/null || echo 0
        return 0
    fi
    conf=$(printf '%s\n' "$conf" | sed -n 's/^[[:space:]]*permissive[[:space:]]*=[[:space:]]*\([0-9][0-9]*\).*/\1/p' | tail -n 1)
    case "$conf" in
        1) echo 1 ;;
        *) echo 0 ;;
    esac
}

# Succeeds when this run's --bootstrap installs a new k3s: no reachable cluster and no
# k3s already on this host.
pf_k3s_will_install() {
    [ "${PF_ASSUME_NODE:-}" = "true" ] || return 1
    ! { command -v k3s >/dev/null 2>&1 && [ -f /etc/rancher/k3s/k3s.yaml ]; }
}

# The k3s release's name for this host's architecture: amd64 or arm64.
pf_k3s_arch() {
    case "$(uname -m 2>/dev/null)" in
        aarch64|arm64) echo arm64 ;;
        *) echo amd64 ;;
    esac
}

pf_selinux_mode() {
    if command -v getenforce >/dev/null 2>&1; then
        getenforce 2>/dev/null | head -n 1
    fi
}

# Succeeds when this run installs the k3s-selinux RPM for a new k3s: a RHEL-family host
# with SELinux policy files, the RPM not skipped (install_k3s_selinux).
pf_k3s_selinux_rpm() {
    pf_k3s_will_install || return 1
    k3s_selinux_rpm_wanted
}

# The SELinux packages the installer's dnf install of k3s-selinux needs, read with
# rpm -q only.
pf_check_selinux_rpms() {
    local level=WARN
    pf_k3s_selinux_rpm || return 0
    [ "$(pf_selinux_mode)" = Enforcing ] && level=FAIL
    if ! command -v rpm >/dev/null 2>&1; then
        pf_rec INFO "SELinux packages" "not checked (no rpm)"
    elif ! rpm -q container-selinux >/dev/null 2>&1; then
        pf_rec "$level" "SELinux packages" "container-selinux not installed; the installer installs it with dnf from your OS repositories, then k3s-selinux from $KLYRO_CDN" \
            "dnf must reach your OS repos (Satellite/CDN) to install container-selinux, or install container-selinux before running the installer"
    elif rpm -q k3s-selinux >/dev/null 2>&1; then
        pf_rec PASS "SELinux packages" "container-selinux and k3s-selinux installed"
    else
        pf_rec PASS "SELinux packages" "container-selinux installed; k3s-selinux comes from $KLYRO_CDN (Network section)"
    fi
}

pf_check_selinux() {
    local mode
    mode=$(pf_selinux_mode)
    if [ -z "$mode" ]; then
        pf_rec INFO SELinux "not installed (no getenforce)"
    elif [ "$mode" = "Enforcing" ] && [ -n "$K3S_DATA_DIR" ] && pf_k3s_will_install; then
        pf_rec FAIL SELinux "Enforcing, and --data-dir is unsupported under SELinux enforcing" \
            "drop --data-dir (k3s then uses $K3S_DATA_DIR_DEFAULT; mount the bigger volume there)"
    elif [ "$mode" = "Enforcing" ] && [ -n "$K3S_DATA_DIR" ]; then
        pf_rec WARN SELinux "Enforcing; --data-dir is ignored: existing cluster keeps its data dir" "drop --data-dir"
    else
        pf_rec INFO SELinux "$mode"
    fi
}

pf_check_cluster() {
    local ver major lead="reachable" ok=PASS state
    if [ "$bootstrap_cluster" = "true" ]; then
        if [ "$PF_CLUSTER_UP" != "true" ]; then
            state=$(systemctl is-active k3s 2>/dev/null || true)
            if pf_k3s_will_install; then
                pf_rec INFO Cluster "k3s will be installed"
            elif [ -z "$state" ] || [ "$state" = active ]; then
                pf_rec INFO Cluster "existing k3s found"
            else
                pf_rec FAIL Cluster "existing k3s found, but its service is $state: --bootstrap reuses it and does not start it" \
                    "start it (systemctl start k3s) and check journalctl -u k3s until kubectl get nodes shows Ready"
            fi
            return 0
        fi
        lead="existing cluster reachable, --bootstrap will use it" ok=INFO
    fi
    if ! command -v kubectl >/dev/null 2>&1; then
        pf_rec FAIL Cluster "kubectl not found" \
            "install kubectl (https://kubernetes.io/docs/tasks/tools/), or rerun with --bootstrap to install k3s"
    elif [ "$PF_CLUSTER_UP" != "true" ]; then
        pf_rec FAIL Cluster "cannot connect to the Kubernetes cluster (kubectl cluster-info)" \
            "check the kubeconfig (~/.kube/config) and kubectl cluster-info, or rerun with --bootstrap to install k3s"
    elif [ "$bootstrap_cluster" = "true" ] && kubectl get crd helmcharts.helm.cattle.io --request-timeout=10s >/dev/null 2>&1; then
        pf_rec "$ok" Cluster "$lead (kubectl, k3s Helm controller)"
    elif ! command -v helm >/dev/null 2>&1; then
        pf_rec FAIL Cluster "$lead, but helm not found" "install Helm 3 (https://helm.sh/docs/intro/install/)"
    else
        ver=$(helm version --short 2>/dev/null | grep -oE 'v[0-9]+\.[0-9]+' | head -n 1)
        major=$(printf '%s\n' "$ver" | cut -d. -f1 | tr -d 'v')
        case "$major" in
            ''|*[!0-9]*|[0-2]) pf_rec FAIL Cluster "$lead, but Helm 3.x required (found: ${ver:-unknown})" "install Helm 3 (https://helm.sh/docs/intro/install/)" ;;
            *) pf_rec "$ok" Cluster "$lead (kubectl, helm $ver)" ;;
        esac
    fi
    [ "$PF_CLUSTER_UP" = "true" ] || return 0
    if ! kubectl auth can-i create namespace --request-timeout=10s >/dev/null 2>&1; then
        pf_rec FAIL "Cluster permissions" "the kubeconfig cannot create namespaces (kubectl auth can-i create namespace)" \
            "use a kubeconfig with cluster-admin or equivalent permissions"
    elif ! kubectl auth can-i create secret --namespace="$NAMESPACE" --request-timeout=10s >/dev/null 2>&1; then
        pf_rec FAIL "Cluster permissions" "the kubeconfig cannot create secrets in $NAMESPACE (kubectl auth can-i create secret)" \
            "use a kubeconfig with cluster-admin or equivalent permissions"
    else
        pf_rec PASS "Cluster permissions" "can create namespaces and secrets in $NAMESPACE"
    fi
}

pf_machine() {
    pf_section "Machine"
    pf_check_os
    pf_check_cpu_mem
    PF_CLUSTER_UP=false
    if command -v kubectl >/dev/null 2>&1 && kubectl cluster-info --request-timeout=10s >/dev/null 2>&1; then
        PF_CLUSTER_UP=true
    fi
    PF_ASSUME_NODE=false
    if [ "$bootstrap_cluster" = "true" ] && [ "$PF_CLUSTER_UP" != "true" ]; then
        PF_ASSUME_NODE=true
        eval_disk_space install
    else
        eval_disk_space
    fi
    EV_DETAIL=${EV_DETAIL#Disk: }
    if [ "$EV_STATUS" = fail ] || [ "$EV_STATUS" = warn ]; then
        if [ -z "$K3S_DATA_DIR" ] && pf_k3s_will_install && [ "$(pf_selinux_mode)" = Enforcing ]; then
            EV_FIX="free space or grow the volume, or mount a bigger volume at ${K3S_DATA_DIR_DEFAULT%/*} before the install (SELinux is Enforcing, so --data-dir is unsupported) (sizing: docs/INSTALL.md §1)"
        fi
    fi
    case "$EV_FIX" in "Free space "*) EV_FIX="free space ${EV_FIX#Free space }" ;; esac
    pf_ev_rec "Disk (k3s data dir)"
    eval_root_or_sudo preflight
    if [ "$EV_STATUS" = fail ] && [ "$PF_CLUSTER_UP" = true ]; then
        EV_STATUS=warn EV_DETAIL="not root and no passwordless sudo; --bootstrap reuses the reachable cluster, which needs neither"
    fi
    pf_ev_rec "Root/sudo"
    AS_ROOT_SUDO=false PF_NOROOT=false
    if [ "$(id -u)" -ne 0 ]; then
        if [ "$EV_STATUS" = "ok" ]; then
            AS_ROOT_SUDO=true
        else
            PF_NOROOT=true
        fi
    fi
    pf_check_selinux
    pf_check_selinux_rpms
    eval_fapolicyd
    if [ "$EV_STATUS" = warn ] && pf_k3s_will_install; then
        pf_rec INFO fapolicyd "active and no rule allows /var/lib/rancher/: --bootstrap adds $FAPOLICYD_RULES_DIR/80-k3s.rules, trusts the k3s binary and reloads fapolicyd before k3s starts"
    else
        if [ "$EV_STATUS" = warn ]; then
            case "$(pf_fapolicyd_permissive)" in
                1) EV_DETAIL="fapolicyd is active in permissive mode (permissive = 1 in $FAPOLICYD_CONF) and no rule allows /var/lib/rancher/: it logs the binaries k3s unpacks there but does not block them; k3s stops running once fapolicyd enforces" ;;
                0) ;;
                *) EV_DETAIL="$EV_DETAIL (could not read $FAPOLICYD_CONF to tell whether fapolicyd enforces or is permissive)" ;;
            esac
        fi
        pf_ev_rec fapolicyd root
    fi
    eval_pod_network_firewall
    if [ "$EV_STATUS" = warn ] && pf_k3s_will_install; then
        pf_rec INFO "firewalld (pod networks)" "the pod and service networks are not trusted: --bootstrap puts them in zone trusted (permanent and runtime) before k3s starts"
    else
        pf_ev_rec "firewalld (pod networks)" root
    fi
    pf_check_cluster
}

# host:port of URL $1 (443 for https, 80 for http when it names no port).
pf_url_hostport() {
    local rest
    rest=${1#*://}
    rest=${rest%%/*}
    rest=${rest##*@}
    case "$rest" in
        *:*) echo "$rest" ;;
        *) case "$1" in http://*) echo "$rest:80" ;; *) echo "$rest:443" ;; esac ;;
    esac
}

# This shell's HTTPS proxy as curl picks it: https_proxy before HTTPS_PROXY.
pf_env_proxy() {
    printf '%s' "${https_proxy:-${HTTPS_PROXY:-}}"
}

# Runs curl along route $1 (host, node or pod, as pf_probe describes) with the preflight
# timeouts (--max-time $PF_MAX_TIME) and the remaining arguments.
pf_curl() {
    local via="$1"
    shift
    if [ "$via" = node ] && [ -n "$PROXY_URL" ]; then
        set -- --proxy "$PROXY_URL" --noproxy "$(node_no_proxy)" "$@"
    fi
    if [ "$via" = pod ]; then
        if [ -z "$PROXY_URL" ]; then
            set -- --noproxy '*' "$@"
        elif [ -n "$NO_PROXY_EXTRA" ]; then
            set -- --proxy "$PROXY_URL" --noproxy "$NO_PROXY_EXTRA" "$@"
        else
            set -- --proxy "$PROXY_URL" "$@"
        fi
        ( unset NO_PROXY no_proxy; curl --connect-timeout 8 --max-time "$PF_MAX_TIME" "$@" </dev/null )
        return
    fi
    curl --connect-timeout 8 --max-time "$PF_MAX_TIME" "$@" </dev/null
}

# Probes URL $1 along route $2: host (the installer's own curl and helm: this shell's proxy
# environment), node (the k3s and containerd of --bootstrap: --proxy with the NO_PROXY
# bootstrap_k3s_cluster gives k3s, else this shell's proxy environment) or pod (--proxy
# and --no-proxy, else direct). Further arguments go to curl. Sets P_CODE (000 when
# nothing answered), P_RC, P_ERR (one line), P_DNS (resolved, not resolved or unknown) and
# P_DENIED: the redacted proxy URL when the answer came from that proxy, not the origin
# (pf_proxy_denial), else empty. A proxy's own answer counts as no answer: P_CODE 000,
# P_ERR saying what the proxy answered.
pf_probe() {
    local url="$1" via="$2" out host proxy why
    shift 2
    out=$(pf_curl "$via" -sS -o /dev/null -D - -w 'PFCODE:%{http_code}' "$@" "$url" 2>&1)
    P_RC=$?
    P_CODE=$(printf '%s\n' "$out" | sed -n 's/.*PFCODE:\([0-9][0-9]*\).*/\1/p' | head -n 1)
    [ -n "$P_CODE" ] || P_CODE=000
    P_ERR=$(printf '%s\n' "$out" | sed 's/PFCODE:[0-9]*//' | pf_curl_error)
    P_DENIED=""
    host=$(pf_url_hostport "$url")
    host=${host%:*}
    if [ "$P_CODE" != 000 ]; then
        proxy=$(pf_route_proxy "$via" "$host")
        if [ -n "$proxy" ]; then
            why=$(printf '%s\n' "$out" | pf_proxy_denial "$P_CODE")
            if [ -n "$why" ]; then
                P_DENIED=$(pf_redact_url "$proxy")
                P_ERR="the proxy answered itself ($why)"
                P_CODE=000
                P_DNS=""
                return 0
            fi
        fi
    fi
    if [ "$P_CODE" != 000 ]; then
        P_DNS=resolved
    elif [ "$P_RC" = 6 ]; then
        P_DNS="not resolved"
    elif command -v getent >/dev/null 2>&1; then
        if getent hosts "$host" >/dev/null 2>&1; then
            P_DNS=resolved
        else
            P_DNS="not resolved"
        fi
    else
        P_DNS=unknown
    fi
}

# Reads the response headers curl -D - printed for a request that went through a proxy and
# prints why its final answer, HTTP $1, came from the proxy rather than the origin, or
# nothing. A TLS-inspecting proxy that refuses a host answers inside the tunnel with its own
# page, which looks like any HTTP answer. Proxy-generated, in this order:
#   - an X-Squid-Error header, any status: Squid sets it only on its own error pages;
#   - a Proxy-Status header with an error parameter (RFC 9209);
#   - HTTP 407 (proxy authentication required);
#   - HTTP 403 or 5xx whose Server header names a proxy product.
# A Via header alone is not proof: proxies add it to the origin's answers they forward too,
# and an origin's own 403, 404 or 5xx (the Klyro hosts, Docker Hub's CDN) carry no
# proxy-error header, so they still count as answers.
pf_proxy_denial() {
    awk -v code="$1" '
        { sub(/\r$/, ""); l = tolower($0) }
        l ~ /^http\// { sq = ""; ps = ""; srv = ""; next }
        l ~ /^x-squid-error:/ { sq = $0 }
        l ~ /^proxy-status:/ && l ~ /error=/ { ps = $0 }
        l ~ /^server:/ { srv = $0 }
        END {
            if (sq != "") { print "HTTP " code ", " sq; exit }
            if (ps != "") { print "HTTP " code ", " ps; exit }
            if (code == "407") { print "HTTP 407, proxy authentication required"; exit }
            p = "squid|zscaler|bluecoat|proxysg|websense|forcepoint|mcafee web gateway|skyhigh|netskope|fortigate|fortiproxy|ironport|tinyproxy|privoxy|ccproxy"
            if ((code == "403" || code ~ /^5/) && tolower(srv) ~ p) print "HTTP " code ", " srv
        }'
}

# Prints the first curl error line on stdin, on one line: curl follows some errors (60)
# with a paragraph of advice that the report does not need.
pf_curl_error() {
    grep '^curl: ' | head -n 1 | tr '\t\r' '  ' | sed 's/  */ /g; s/ *$//'
}

# Succeeds when host $1 matches the comma-separated no-proxy list $2 as curl matches it:
# "*", the host itself, or a domain the host is under.
pf_no_proxy_match() {
    printf '%s\n' "$2" | tr ',' '\n' | tr -d ' ' | {
        while IFS= read -r e; do
            e=${e#.}
            [ -n "$e" ] || continue
            [ "$e" = "*" ] && exit 0
            [ "$1" = "$e" ] && exit 0
            case "$1" in *."$e") exit 0 ;; esac
        done
        exit 1
    }
}

# Prints the proxy route $1 (host, node or pod) uses for host $2, or nothing when it goes
# direct: host takes this shell's proxy environment, node --proxy with the NO_PROXY
# bootstrap_k3s_cluster gives k3s (else this shell's environment), pod --proxy and
# --no-proxy.
pf_route_proxy() {
    local shell_np="${NO_PROXY:-}${no_proxy:+,$no_proxy}" env_proxy
    env_proxy=$(pf_env_proxy)
    case "$1" in
        pod)
            if [ -n "$PROXY_URL" ] && ! pf_no_proxy_match "$2" "$NO_PROXY_EXTRA"; then
                printf '%s' "$PROXY_URL"
            fi
            ;;
        node)
            if [ -n "$PROXY_URL" ]; then
                pf_no_proxy_match "$2" "$shell_np,$NO_PROXY_EXTRA,localhost,127.0.0.1" || printf '%s' "$PROXY_URL"
            elif [ -n "$env_proxy" ] && ! pf_no_proxy_match "$2" "$shell_np"; then
                printf '%s' "$env_proxy"
            fi
            ;;
        *)
            if [ -n "$env_proxy" ] && ! pf_no_proxy_match "$2" "$shell_np"; then
                printf '%s' "$env_proxy"
            fi
            ;;
    esac
    return 0
}

# How route $1 (host, node or pod) reaches host $2, for the report.
pf_net_route() {
    local proxy
    proxy=$(pf_route_proxy "$1" "${2:-}")
    if [ -n "$proxy" ]; then
        if [ "$1" != host ] && [ "$proxy" = "$PROXY_URL" ]; then
            echo "through --proxy $(pf_redact_url "$proxy")"
        else
            echo "through HTTPS_PROXY $(pf_redact_url "$proxy")"
        fi
    elif [ "$1" = pod ] && [ -z "$PROXY_URL" ]; then
        echo "direct (no --proxy)"
    elif { [ "$1" != host ] && [ -n "$PROXY_URL" ]; } || { [ "$1" != pod ] && [ -n "$(pf_env_proxy)" ]; }; then
        echo "direct (no-proxy)"
    else
        echo "direct"
    fi
}

# pf_net_route without parentheses, to sit inside them: "direct, no --proxy".
pf_net_route_flat() {
    pf_net_route "$@" | sed 's/ (\(.*\))$/, \1/'
}

pf_containerd_fix() {
    echo "configure the cluster's containerd/registry proxy or mirror for $1"
}

# Records one reachability line: name $1, URL $2, route $3 (host, node or pod), detail
# suffix $4, and when it is unreachable status $5 (default FAIL) with consequence $6
# appended to the fix.
# Fails only when the time budget is spent.
pf_net_check() {
    local name="$1" url="$2" via="$3" note="${4:-}" level="${5:-FAIL}" impact="${6:+; $6}" hp host route env_proxy fix ctrd="" cacert=""
    pf_budget_ok || return 1
    [ "$via" = pod ] && [ "$name" = "Klyro registry (k3s/containerd)" ] && ctrd=yes
    hp=$(pf_url_hostport "$url")
    host=${hp%:*}
    route=$(pf_net_route "$via" "$host")
    pf_probe "$url" "$via"
    if [ "$P_RC" = 60 ] && [ "$via" = pod ] && [ -z "$ctrd" ] && pf_ca_file_ok && pf_budget_ok; then
        pf_probe "$url" pod --cacert "$CA_FILE"
        if [ "$P_CODE" != 000 ]; then
            route="$route, verified with --ca-file"
            cacert="$CA_FILE"
        fi
    fi
    if [ "$P_CODE" != 000 ]; then
        pf_rec PASS "$name" "$hp reachable (HTTP $P_CODE), $route$note"
        case "$name" in
            "gRPC ("*) pf_check_h2 "$url" "$route" "$cacert" ;;
        esac
        return 0
    fi
    if [ "$P_RC" = 60 ]; then
        pf_rec "$level" "$name" "$hp answers, but its TLS certificate does not verify, $route: $P_ERR$note" \
            "see the TLS section: trust the root CA of the proxy that re-signs it$impact"
        return 0
    fi
    if [ -n "$P_DENIED" ]; then
        pf_rec "$level" "$name" "$hp blocked by the proxy, $route: $P_ERR$note" \
            "the proxy at $P_DENIED denied $host: allow $hp on the proxy$impact"
        return 0
    fi
    local err="${P_ERR:-no answer}" dns="$P_DNS"
    env_proxy=$(pf_env_proxy)
    if [ "$via" = pod ] && [ -z "$PROXY_URL" ] && [ -n "$env_proxy" ] && pf_budget_ok; then
        pf_probe "$url" host
        if [ "$P_CODE" != 000 ] && [ -n "$ctrd" ]; then
            pf_rec "$level" "$name" \
                "$hp unreachable directly (it answers through HTTPS_PROXY $(pf_redact_url "$env_proxy"))$note" \
                "$(pf_containerd_fix "$hp")$impact"
            return 0
        elif [ "$P_CODE" != 000 ]; then
            pf_rec "$level" "$name" \
                "$hp unreachable, no --proxy given, pods would go direct (it answers through HTTPS_PROXY $(pf_redact_url "$env_proxy"))$note" \
                "add --proxy http://<host>:<port>; the agent pods use your shell's HTTPS_PROXY only when it is an http:// URL$impact"
            return 0
        fi
    fi
    case "$ctrd$route" in
        yes*)
            fix=$(pf_containerd_fix "$hp")
            ;;
        "through --proxy"*)
            fix="allow $hp on your proxy (--proxy $(pf_redact_url "$PROXY_URL"))"
            dns=""
            ;;
        "through HTTPS_PROXY"*)
            fix="allow $hp on your proxy (HTTPS_PROXY $(pf_redact_url "$env_proxy"))"
            dns=""
            ;;
        *)
            if [ "$dns" = "not resolved" ]; then
                fix="make $host resolvable from this host and allow outbound HTTPS to $hp"
            else
                fix="allow outbound HTTPS from this host to $hp"
            fi
            if [ "$via" = host ] && [ -n "$PROXY_URL" ] && [ "$route" = direct ]; then
                fix="$fix, or export HTTPS_PROXY and HTTP_PROXY (the --proxy URL, $(pf_redact_url "$PROXY_URL")) and NO_PROXY in the shell that runs the installer: --proxy covers only k3s and the pods, the installer's own downloads use the shell's proxy environment"
            fi
            ;;
    esac
    pf_rec "$level" "$name" "$hp unreachable, $route: $err${dns:+; local DNS $dns}$note" "$fix$impact"
}

# Records whether URL $1 negotiates HTTP/2 on the pod route $2 (trusting CA file $3 when
# set): grpc-go refuses a TLS server that does not offer ALPN h2, so a proxy that
# re-encrypts the gRPC host as HTTP/1.1 breaks the control stream.
pf_check_h2() {
    local hp v
    hp=$(pf_url_hostport "$1")
    if ! curl -V 2>/dev/null | grep -qi '^features:.*http2'; then
        pf_rec INFO "gRPC HTTP/2" "not checked (this host's curl has no HTTP/2 support)"
        return 0
    fi
    pf_budget_ok || return 0
    if [ -n "$3" ]; then
        v=$(pf_curl pod -s -o /dev/null --http2 -w '%{http_version}' --cacert "$3" "$1" 2>/dev/null)
    else
        v=$(pf_curl pod -s -o /dev/null --http2 -w '%{http_version}' "$1" 2>/dev/null)
    fi
    case "$v" in
        2) pf_rec PASS "gRPC HTTP/2" "$hp negotiates HTTP/2 (ALPN h2), $2" ;;
        1*) pf_rec FAIL "gRPC HTTP/2" "$hp answers over HTTP/$v, not HTTP/2, $2: the agent's gRPC stream needs ALPN h2" \
            "exempt ${hp%:*} from TLS inspection on your proxy, or make the proxy speak HTTP/2 on both sides" ;;
        *) pf_rec INFO "gRPC HTTP/2" "not checked (no answer to the HTTP/2 probe)" ;;
    esac
}

# The token endpoint the agent pods call: an AUTH_ENDPOINT the caller set, else the one
# Klyro Cloud hands out, <Klyro API>/api/v1/auth/token (the gateway token proxy).
pf_auth_url() {
    if [ -n "${PF_AUTH_ENDPOINT_ENV:-}" ]; then
        printf '%s\n' "$PF_AUTH_ENDPOINT_ENV"
    else
        printf '%s\n' "${KLYRO_API_URL%/}/api/v1/auth/token"
    fi
}

# The reachability targets, one "route|name|url|status|consequence" per line; status
# (default FAIL) and consequence are for an unreachable target.
pf_net_targets() {
    echo "host|Klyro API|$KLYRO_API_URL"
    echo "host|Klyro registry|https://$KLYRO_REGISTRY/v2/"
    echo "host|Installer (get.klyro.security)|https://get.klyro.security/"
    if pf_k3s_will_install; then
        echo "host|k3s installer|$(k3s_installer_url)|FAIL|the installer downloads the k3s installer from there"
        echo "node|k3s binary|$(k3s_artifact_url)/$(k3s_url_version "$(k3s_version)")/sha256sum-$(pf_k3s_arch).txt|FAIL|the k3s installer downloads k3s from there"
        if pf_k3s_selinux_rpm; then
            echo "node|k3s-selinux repository|https://$KLYRO_CDN/rancher-rpm/public.key|FAIL|the installer installs the k3s-selinux RPM from there with dnf and stops when dnf fails"
        fi
    fi
    echo "pod|gRPC ($GRPC_ENDPOINT)|https://$GRPC_ENDPOINT/"
    echo "pod|Auth (token endpoint)|$(pf_auth_url)"
    if pf_has researcher; then
        echo "pod|LLM gateway|$LLM_GATEWAY_URL"
    fi
    echo "pod|OTel ingest|https://$(otel_ingest_host_for_env "$GRPC_ENDPOINT")/"
    echo "pod|Result uploads|https://agent-upload.${KLYRO_REGISTRY#registry.}/|WARN|the install still completes, but runs cannot upload their results"
    if pf_has researcher && [ -z "$CHART_REPO" ]; then
        echo "pod|Researcher self-upgrade (ghcr.io)|https://ghcr.io/v2/|WARN|the install still completes, but the Researcher agent cannot self-upgrade; or pass --chart-repo oci://$(klyro_image_registry)/charts"
    fi
    if pf_k3s_will_install; then
        echo "node|Klyro registry (k3s/containerd)|https://$KLYRO_REGISTRY/v2/"
        if [ -e "$(new_k3s_registries_file)" ]; then
            echo "node|registry-1.docker.io|https://registry-1.docker.io/v2/"
            echo "node|auth.docker.io|https://auth.docker.io/token"
            echo "node|production.cloudflare.docker.com|https://production.cloudflare.docker.com/"
            echo "node|production.cloudfront.docker.com|https://production.cloudfront.docker.com/"
        fi
    else
        echo "pod|Klyro registry (k3s/containerd)|https://$KLYRO_REGISTRY/v2/"
    fi
}

pf_network() {
    local via name url level impact note env_proxy
    pf_section "Network"
    env_proxy=$(pf_env_proxy)
    pf_rec INFO Proxy "--proxy $(pf_redact_url "${PROXY_URL:-none}")${PROXY_AUTO:+ (auto-detected from HTTPS_PROXY)}, shell HTTPS_PROXY $(pf_redact_url "${env_proxy:-none}")${NO_PROXY_EXTRA:+, --no-proxy $NO_PROXY_EXTRA}"
    while IFS='|' read -r via name url level impact; do
        [ -n "$url" ] || continue
        note=""
        if [ "$name" = "Klyro registry (k3s/containerd)" ] && ! pf_k3s_will_install; then
            note="; existing cluster's containerd proxy not inspected"
        fi
        pf_net_check "$name" "$url" "$via" "$note" "$level" "$impact" || return 0
    done <<PF_EOF
$(pf_net_targets)
PF_EOF
}
PF_TLS_OS_FIX="add the proxy's root CA to the OS trust store: RHEL \`cp ca.pem /etc/pki/ca-trust/source/anchors/ && update-ca-trust\`, Ubuntu \`cp ca.pem /usr/local/share/ca-certificates/proxy-ca.crt && update-ca-certificates\`"
PF_TLS_CA_FIX="pass --ca-file <proxy root CA PEM>"

# Succeeds when --ca-file names a readable PEM bundle.
pf_ca_file_ok() {
    [ -n "$CA_FILE" ] && [ -r "$CA_FILE" ] && grep -q -- '-----BEGIN CERTIFICATE-----' "$CA_FILE"
}

# Prints the issuer of the certificate host:port $1 presents along route $2 (host, node or
# pod) on one line, or nothing when openssl cannot read it. Needs timeout: openssl s_client
# has no deadline of its own.
pf_tls_issuer() {
    local hp="$1" via="$2" proxy
    proxy=$(pf_route_proxy "$via" "${hp%:*}")
    case "$proxy" in
        "") ;;
        *://*) proxy=$(pf_url_hostport "$proxy") ;;
        *) proxy=$(pf_url_hostport "http://$proxy") ;;
    esac
    set -- s_client -connect "$hp" -servername "${hp%:*}"
    [ -n "$proxy" ] && set -- "$@" -proxy "$proxy"
    timeout 15 openssl "$@" </dev/null 2>/dev/null | openssl x509 -noout -issuer 2>/dev/null \
        | tr '\n\t' '  ' | sed 's/^ *issuer= *//; s/   */ /g; s/ *$//'
}

# Succeeds when issuer $2 of host:port $1 shows a re-signed certificate: the Klyro
# endpoints carry Amazon-issued certificates.
pf_tls_resigned() {
    case "${1%:*}" in
        *.klyro.security) ;;
        *) return 1 ;;
    esac
    [ -n "$2" ] && ! printf '%s' "$2" | grep -Eq 'O ?= ?Amazon([,/ ]|$)'
}

# Whether something on the way re-signs TLS: the installer, k3s and containerd verify with
# the OS trust store (KLYRO_API_URL on the host route, the registry on the route its puller
# takes), the agent pods with --ca-file (the gRPC endpoint on the pod route). A certificate
# that fails verification but answers with -k is re-signed; with openssl, so is a Klyro
# certificate not issued by Amazon, even when the OS trust store accepts it.
pf_tls() {
    local via url hp route reg_via=host intercepted="" host_bad="" host_ok="" host_err=""
    local first_hp="" first_via="" pod_state=unreachable pod_url="https://$GRPC_ENDPOINT/" pod_hp api_hp
    local api_int=false have_openssl=false api_issuer="" pod_issuer="" issuer=""
    pf_section "TLS"
    command -v openssl >/dev/null 2>&1 && have_openssl=true
    if [ "$have_openssl" = true ] && ! command -v timeout >/dev/null 2>&1; then
        have_openssl=notimeout
    fi
    pf_k3s_will_install && reg_via=node
    api_hp=$(pf_url_hostport "$KLYRO_API_URL")
    pod_hp=$(pf_url_hostport "$pod_url")
    while IFS='|' read -r via url; do
        [ -n "$url" ] || continue
        pf_budget_ok || return 0
        hp=$(pf_url_hostport "$url")
        pf_probe "$url" "$via"
        if [ "$P_RC" != 60 ]; then
            if [ "$P_CODE" != 000 ]; then
                if [ "$via" = pod ]; then
                    pod_state=ok
                else
                    host_ok="${host_ok:+$host_ok, }$hp"
                fi
            fi
            continue
        fi
        if [ "$via" != pod ]; then
            host_bad="${host_bad:+$host_bad, }$hp"
            [ -n "$host_err" ] || host_err="$P_ERR"
        fi
        pf_budget_ok || return 0
        pf_probe "$url" "$via" -k
        [ "$P_CODE" != 000 ] || [ -n "$P_DENIED" ] || continue
        [ "$via" = pod ] && pod_state=intercepted
        [ "$via" = host ] && [ "$url" = "$KLYRO_API_URL" ] && api_int=true
        intercepted="${intercepted:+$intercepted, }$hp ($(pf_net_route_flat "$via" "${hp%:*}"))"
        if [ -z "$first_hp" ]; then
            first_hp="$hp"
            first_via="$via"
        fi
    done <<PF_EOF
host|$KLYRO_API_URL
$reg_via|https://$KLYRO_REGISTRY/v2/
pod|$pod_url
PF_EOF

    if [ "$have_openssl" = true ]; then
        pf_budget_ok || return 0
        api_issuer=$(pf_tls_issuer "$api_hp" host)
        pf_budget_ok || return 0
        pod_issuer=$(pf_tls_issuer "$pod_hp" pod)
        if [ "$api_int" = false ] && pf_tls_resigned "$api_hp" "$api_issuer"; then
            api_int=true
            intercepted="$api_hp ($(pf_net_route_flat host "${api_hp%:*}"))${intercepted:+, $intercepted}"
            first_hp="$api_hp"
            first_via=host
        fi
        if [ "$pod_state" != intercepted ] && pf_tls_resigned "$pod_hp" "$pod_issuer"; then
            pod_state=intercepted
            intercepted="${intercepted:+$intercepted, }$pod_hp ($(pf_net_route_flat pod "${pod_hp%:*}"))"
            [ -n "$first_hp" ] || { first_hp="$pod_hp"; first_via=pod; }
        fi
        if [ -z "$intercepted" ] || [ "$first_hp|$first_via" = "$api_hp|host" ]; then
            issuer="$api_issuer"
        elif [ "$first_hp|$first_via" = "$pod_hp|pod" ]; then
            issuer="$pod_issuer"
        else
            pf_budget_ok || return 0
            issuer=$(pf_tls_issuer "$first_hp" "$first_via")
        fi
        issuer="issuer ${issuer:-unknown (openssl could not read the certificate)}"
    elif [ "$have_openssl" = notimeout ]; then
        issuer="issuer not checked (no timeout command to bound openssl)"
    else
        issuer="issuer not checked (no openssl)"
    fi

    if [ -n "$intercepted" ]; then
        pf_rec INFO "TLS interception" "intercepted on $intercepted; $issuer"
    else
        pf_rec INFO "TLS interception" "none detected; $issuer"
    fi

    if [ -n "$host_bad" ]; then
        pf_rec FAIL "Host trust store" "the OS trust store does not verify $host_bad ($host_err)" "$PF_TLS_OS_FIX"
    elif [ -n "$host_ok" ]; then
        pf_rec PASS "Host trust store" "$host_ok verify with the OS trust store"
    else
        pf_rec INFO "Host trust store" "not checked: the Klyro API and registry did not answer (see Network)"
    fi

    route=$(pf_net_route pod "${pod_hp%:*}")
    if [ -n "$CA_FILE" ] && ! pf_ca_file_ok; then
        pf_rec FAIL "Pod trust (--ca-file)" "--ca-file $CA_FILE is not a readable PEM certificate bundle" "$PF_TLS_CA_FIX"
    elif [ -z "$intercepted" ]; then
        pf_rec INFO "Pod trust (--ca-file)" "not needed (no TLS interception detected)${CA_FILE:+; the pods will also trust $CA_FILE}"
    elif [ "$pod_state" = ok ]; then
        pf_rec INFO "Pod trust (--ca-file)" "not needed (the pod route, $route, is not intercepted)${CA_FILE:+; the pods will also trust $CA_FILE}"
    elif [ -z "$CA_FILE" ]; then
        pf_rec FAIL "Pod trust (--ca-file)" "TLS is intercepted and no --ca-file given: the agent pods would reject the re-signed certificates" "$PF_TLS_CA_FIX"
    else
        pf_budget_ok || return 0
        pf_probe "$pod_url" pod --cacert "$CA_FILE"
        if [ "$P_CODE" != 000 ]; then
            pf_rec PASS "Pod trust (--ca-file)" "$CA_FILE verifies $pod_hp, $route"
        elif [ "$P_RC" = 60 ] || [ "$P_RC" = 77 ]; then
            pf_rec FAIL "Pod trust (--ca-file)" "$CA_FILE does not verify $pod_hp, $route: $P_ERR" "$PF_TLS_CA_FIX"
        else
            pf_rec WARN "Pod trust (--ca-file)" "not verified: $pod_hp did not answer on the pod route, $route: $P_ERR" \
                "fix the Network failures above, then rerun --preflight"
        fi
    fi
}

# Bedrock reachability only: klyro onboard calls Bedrock from this host as a local process,
# so the probes take the host route. No credentials are sent.
pf_bedrock() {
    pf_section "Bedrock (network only)"
    case "$BEDROCK_REGION" in
        ""|*[!a-z0-9-]*)
            pf_rec FAIL "Bedrock region" "\"$BEDROCK_REGION\" is not an AWS region name" \
                "pass --bedrock-region <region>, for example us-east-1"
            return 0
            ;;
    esac
    pf_rec INFO Bedrock "Model access is checked by klyro onboard; it calls Bedrock from this host through this shell's proxy environment, as these probes do"
    pf_net_check "AWS STS ($BEDROCK_REGION)" "https://sts.$BEDROCK_REGION.amazonaws.com/" host || return 0
    pf_net_check "Bedrock runtime ($BEDROCK_REGION)" "https://bedrock-runtime.$BEDROCK_REGION.amazonaws.com/" host || return 0
}
PF_OCI_MANIFEST="application/vnd.oci.image.manifest.v1+json"
PF_IMAGE_ACCEPT="application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json"

# Succeeds when product $1 (researcher or mc) is part of this run: --product, else both.
pf_has() {
    case "${PRODUCT:-both}" in
        both|"$1") return 0 ;;
    esac
    return 1
}

# GETs URL $1 along route $2 (further arguments go to curl): sets P_BODY to the response
# body, and P_CODE, P_RC and P_ERR as pf_probe does.
pf_get() {
    local url="$1" via="$2" out
    shift 2
    out=$(pf_curl "$via" -sS -w 'PFCODE:%{http_code}' "$@" "$url" 2>&1)
    P_RC=$?
    P_CODE=$(printf '%s\n' "$out" | sed -n 's/.*PFCODE:\([0-9][0-9]*\).*/\1/p' | tail -n 1)
    [ -n "$P_CODE" ] || P_CODE=000
    P_ERR=$(printf '%s\n' "$out" | sed 's/PFCODE:[0-9]*$//' | pf_curl_error)
    P_BODY=$(printf '%s\n' "$out" | grep -v '^curl: ' | sed 's/PFCODE:[0-9]*$//')
}

# Prints the scalar at dotted key $1 (such as agent.image.tag) of the YAML on stdin, without
# its quotes or comment, or nothing. Block-style mappings only; list items and the lines of
# block scalars are skipped.
pf_yaml_value() {
    awk -v want="$1" -v q="'" '
        BEGIN { n = split(want, w, "."); depth = 0; block = -1 }
        {
            line = $0
            sub(/\r$/, "", line)
            match(line, /^ */)
            ind = RLENGTH
            rest = substr(line, ind + 1)
            if (block >= 0) {
                if (rest == "" || ind > block) next
                block = -1
            }
            if (rest == "" || substr(rest, 1, 1) == "#" || substr(rest, 1, 1) == "-") next
            if (rest !~ /^[A-Za-z0-9_.\/-]+[ \t]*:([ \t]|$)/) next
            key = rest
            sub(/[ \t]*:.*/, "", key)
            val = rest
            sub(/^[^:]*:[ \t]*/, "", val)
            while (depth > 0 && ind <= at[depth]) depth--
            depth++
            at[depth] = ind
            k[depth] = key
            if (val ~ /^[|>]/) block = ind
            if (depth != n) next
            for (i = 1; i <= n; i++) if (k[i] != w[i]) next
            c = substr(val, 1, 1)
            if (c == "\"" || c == q) {
                val = substr(val, 2)
                val = substr(val, 1, index(val, c) - 1)
            } else {
                sub(/[ \t]+#.*/, "", val)
                sub(/[ \t]+$/, "", val)
            }
            print val
            exit
        }'
}

# Prints the highest x.y.z tag of the registry tags/list JSON on stdin.
pf_latest_semver() {
    tr -d ' \t\r\n' | sed -n 's/.*"tags":\[\([^]]*\)\].*/\1/p' | tr ',' '\n' | tr -d '"' \
        | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1
}

# Succeeds when curl error $1 is a timeout after the connection was made (the server was slow
# to answer), not a connect, DNS or TLS handshake timeout.
pf_answer_timeout() {
    case "$1" in
        *"Operation timed out after"*) return 0 ;;
    esac
    return 1
}

# Succeeds when the Network section recorded line $1 as PASS.
pf_line_passed() {
    printf '%s' "$PF_LINES" | grep -qF "Network${PF_US}PASS${PF_US}$1${PF_US}"
}

# Records line $1 for the registry request $2 that just got no usable answer along route $3,
# with detail suffix $4: a WARN when the registry accepted the connection but answered slower
# than $PF_MAX_TIME s (a pull waits for it), else a FAIL.
pf_registry_fail() {
    local route net=
    route=$(pf_net_route "$3" "$KLYRO_REGISTRY")
    [ "$3" = host ] && net="Klyro registry" || net="Klyro registry (k3s/containerd)"
    if [ "$P_RC" = 28 ] && [ -z "$P_DENIED" ] && pf_answer_timeout "$P_ERR"; then
        pf_rec WARN "$1" "$2 timed out after $PF_MAX_TIME s, $route: $KLYRO_REGISTRY accepted the connection but answered slowly: $P_ERR${4:-}" \
            "the install waits for this answer, so it likely succeeds slowly; if this repeats, check what slows $KLYRO_REGISTRY along this route, then rerun --preflight"
    elif [ "$P_RC" = 60 ]; then
        pf_rec FAIL "$1" "$2: the TLS certificate of $KLYRO_REGISTRY does not verify, $route: $P_ERR${4:-}" \
            "see the TLS section: trust the root CA of the proxy that re-signs it"
    elif [ -n "$P_DENIED" ]; then
        pf_rec FAIL "$1" "$2: $KLYRO_REGISTRY blocked by the proxy, $route: $P_ERR${4:-}" \
            "the proxy at $P_DENIED denied $KLYRO_REGISTRY: allow $KLYRO_REGISTRY:443 on the proxy"
    elif [ "$P_CODE" = 000 ] && [ "$3" = pod ]; then
        pf_rec FAIL "$1" "$2: $KLYRO_REGISTRY unreachable, $route: ${P_ERR:-no answer}${4:-}" \
            "$(pf_containerd_fix "$KLYRO_REGISTRY:443")"
    elif [ "$P_CODE" = 000 ] && pf_line_passed "$net"; then
        pf_rec FAIL "$1" "$2: $KLYRO_REGISTRY unreachable, $route: ${P_ERR:-no answer}${4:-}" \
            "the Network section reached $KLYRO_REGISTRY:443 but this request did not: check that the route to it is stable, $route, then rerun --preflight"
    elif [ "$P_CODE" = 000 ]; then
        pf_rec FAIL "$1" "$2: $KLYRO_REGISTRY unreachable, $route: ${P_ERR:-no answer}${4:-}" \
            "fix the Klyro registry lines in the Network section, then rerun --preflight"
    else
        pf_rec FAIL "$1" "$2: $KLYRO_REGISTRY answered HTTP $P_CODE, $route${4:-}" "send this report to Klyro"
    fi
}

# Records line $2 for chart $1 (klyro-edge or mc): its latest version, or version $3 when
# given. Adds "<chart> <version>" to PF_CHARTS when it is published.
pf_chart_check() {
    local chart="$1" name="$2" version="$3" base route latest
    base="https://$KLYRO_REGISTRY/v2/${PF_CHART_PATH}/$chart"
    route=$(pf_net_route host "$KLYRO_REGISTRY")
    if [ -n "$version" ]; then
        pf_probe "$base/manifests/$version" host -I -H "Accept: $PF_OCI_MANIFEST"
        case "$P_CODE" in
            200)
                pf_rec PASS "$name" "version $version (--mc-chart-version) published, $route"
                PF_CHARTS="${PF_CHARTS}$chart $version
"
                ;;
            404) pf_rec FAIL "$name" "version $version (--mc-chart-version) is not published on $KLYRO_REGISTRY" \
                "pass a published MC chart version to --mc-chart-version, or leave it out" ;;
            *) pf_registry_fail "$name" "HEAD the $chart chart $version" host ;;
        esac
        return 0
    fi
    pf_get "$base/tags/list" host
    if [ "$P_CODE" != 200 ]; then
        pf_registry_fail "$name" "GET the $chart chart tags" host
        return 0
    fi
    latest=$(printf '%s' "$P_BODY" | pf_latest_semver)
    if [ -z "$latest" ]; then
        pf_rec FAIL "$name" "no chart versions published at oci://$KLYRO_REGISTRY/${PF_CHART_PATH}/$chart" "send this report to Klyro"
        return 0
    fi
    pf_rec PASS "$name" "latest $latest (oci://$KLYRO_REGISTRY/${PF_CHART_PATH}/$chart), $route"
    PF_CHARTS="${PF_CHARTS}$chart $latest
"
}

# Prints the digest of the chart content layer of chart $1 at version $2 (host route).
pf_chart_digest() {
    pf_curl host -sSf -H "Accept: $PF_OCI_MANIFEST" "https://$KLYRO_REGISTRY/v2/${PF_CHART_PATH}/$1/manifests/$2" 2>/dev/null \
        | tr -d '\r\n' | tr '{' '\n' | grep 'application/vnd.cncf.helm.chart.content' \
        | sed -n 's/.*"digest" *: *"\(sha256:[0-9a-f]*\)".*/\1/p' | head -n 1
}

# Streams file $3 of chart $1 from its content blob $2 to stdout: nothing is written to disk.
pf_chart_file() {
    pf_curl host -sSfL "https://$KLYRO_REGISTRY/v2/${PF_CHART_PATH}/$1/blobs/$2" 2>/dev/null \
        | tar -xzOf - "$1/$3" 2>/dev/null
}

# Records one line per image the charts in PF_CHARTS install from the Klyro registry: the
# repository install_image_repository maps each to, with the chart's tag (a subchart's
# default when the chart gives none), HEAD on the route containerd pulls it on. The HEADs
# share one deadline, PF_IMAGE_DEADLINE: $PF_IMAGE_BUDGET_S s, ending at least
# $PF_PRODUCT_RESERVE_S s before the run's deadline.
pf_images() {
    local via=pod note="" chart version digest values sub subvalues key repo tag path checked=" " route
    PF_IMAGE_DEADLINE=$(( $(date +%s) + PF_IMAGE_BUDGET_S ))
    [ "$PF_IMAGE_DEADLINE" -le $(( PF_DEADLINE - PF_PRODUCT_RESERVE_S )) ] \
        || PF_IMAGE_DEADLINE=$(( PF_DEADLINE - PF_PRODUCT_RESERVE_S ))
    if pf_k3s_will_install; then
        via=node
    else
        note="; existing cluster's containerd proxy not inspected"
    fi
    route=$(pf_net_route "$via" "$KLYRO_REGISTRY")
    if ! command -v tar >/dev/null 2>&1; then
        pf_rec INFO Images "not checked (no tar on this host to read the charts)"
        return 0
    fi
    while read -r chart version; do
        [ -n "$version" ] || continue
        pf_budget_ok || return 0
        digest=$(pf_chart_digest "$chart" "$version")
        values=""
        if [ -n "$digest" ] && pf_budget_ok; then
            values=$(pf_chart_file "$chart" "$digest" values.yaml)
        fi
        if [ -z "$values" ]; then
            pf_chart_read_fail "$chart" "$version" "$digest"
            continue
        fi
        sub="" subvalues=""
        for key in $(install_image_keys "$chart"); do
            pf_budget_ok || return 0
            repo=$(printf '%s\n' "$values" | pf_yaml_value "$key.repository")
            tag=$(printf '%s\n' "$values" | pf_yaml_value "$key.tag")
            if [ -z "$tag" ] && [ "${key#*.}" != "$key" ]; then
                if [ "$sub" != "${key%%.*}" ]; then
                    sub="${key%%.*}"
                    subvalues=$(pf_chart_file "$chart" "$digest" "charts/$sub/values.yaml")
                fi
                tag=$(printf '%s\n' "$subvalues" | pf_yaml_value "${key#*.}.tag")
                [ -n "$repo" ] || repo=$(printf '%s\n' "$subvalues" | pf_yaml_value "${key#*.}.repository")
            fi
            repo=$(install_image_repository "$chart" "$key" "$repo")
            if [ -z "$repo" ] || [ -z "$tag" ]; then
                pf_rec INFO "Image $key ($chart chart)" "reference not determined from the chart's values; not checked"
                continue
            fi
            case "$repo" in
                "$KLYRO_REGISTRY"/*) path=${repo#"$KLYRO_REGISTRY"/} ;;
                *)
                    pf_rec INFO "Image $repo:$tag" "not pulled from $KLYRO_REGISTRY; not checked"
                    continue
                    ;;
            esac
            case "$checked" in *" $path:$tag "*) continue ;; esac
            checked="$checked$path:$tag "
            pf_image_check "$path" "$tag" "$via" "$route" "$note"
        done
    done <<PF_EOF
$PF_CHARTS
PF_EOF
    while read -r path; do
        [ -n "$path" ] || continue
        tag=${path##*:}
        path=${path%:*}
        case "$checked" in *" $path:$tag "*) continue ;; esac
        pf_budget_ok || return 0
        pf_image_check "$path" "$tag" "$via" "$route" "$note"
    done <<PF_EOF
$(pf_install_images)
PF_EOF
}

# Records why values.yaml of chart $1 $2 (content blob $3, empty when its manifest gave
# none) could not be read: the manifest or blob request is repeated, once, to name the curl
# error and the route.
pf_chart_read_fail() {
    local url route what
    route=$(pf_net_route host "$KLYRO_REGISTRY")
    pf_budget_ok || return 0
    if [ -z "$3" ]; then
        url="https://$KLYRO_REGISTRY/v2/${PF_CHART_PATH}/$1/manifests/$2"
        what="its manifest"
        pf_probe "$url" host -H "Accept: $PF_OCI_MANIFEST"
    else
        url="https://$KLYRO_REGISTRY/v2/${PF_CHART_PATH}/$1/blobs/$3"
        what="its chart archive"
        pf_probe "$url" host -L
    fi
    if [ -n "$P_DENIED" ]; then
        pf_rec FAIL "Images ($1 chart)" "reading $what (values.yaml of chart $1 $2) was blocked by the proxy, $route: $P_ERR; the install downloads this chart along the same route, so its helm pull fails the same way" \
            "the proxy at $P_DENIED denied $KLYRO_REGISTRY: allow $KLYRO_REGISTRY:443 on the proxy, then rerun --preflight"
    elif [ "$P_RC" = 28 ]; then
        pf_rec WARN "Images ($1 chart)" "not checked: reading $what (values.yaml of chart $1 $2) timed out after 15 s, $route: $P_ERR" \
            "the install downloads this chart along the same route, $route: check that $KLYRO_REGISTRY answers quickly there, then rerun --preflight"
    elif [ "$P_CODE" = 000 ]; then
        pf_rec WARN "Images ($1 chart)" "not checked: reading $what (values.yaml of chart $1 $2) failed, $route: ${P_ERR:-no answer}" \
            "check the route to $KLYRO_REGISTRY, $route, then rerun --preflight"
    else
        pf_rec WARN "Images ($1 chart)" "not checked: could not read values.yaml of chart $1 $2; $what answers HTTP $P_CODE now, $route" \
            "rerun --preflight; if this line repeats, send this report to Klyro"
    fi
}

# The images the installer deploys outside the charts, one path:tag under the Klyro
# registry per line: start_temporal's for the Researcher, and the check pod of
# validate_mc_external_database for an MC on an external database.
pf_install_images() {
    if pf_has researcher; then
        printf '%s\n' library/postgres:15-alpine temporalio/auto-setup:1.24.2 temporalio/ui:2.26.2
    fi
    if pf_has mc && [ "$MC_DB_MODE" = external ]; then
        echo library/postgres:16.4-alpine
    fi
}

# HEADs image $1:$2 on the Klyro registry along route $3, described as $4 with note $5,
# waiting at most $PF_IMAGE_MAX_TIME s and never past PF_IMAGE_DEADLINE.
pf_image_check() {
    local left
    left=$(( PF_IMAGE_DEADLINE - $(date +%s) ))
    if [ "$left" -lt 5 ]; then
        pf_rec WARN "Image $1:$2" "not checked: the time for the image checks ran out, $4$5" \
            "rerun --preflight; if image lines time out again, check what slows $KLYRO_REGISTRY along this route"
        return 0
    fi
    [ "$left" -le "$PF_IMAGE_MAX_TIME" ] || left=$PF_IMAGE_MAX_TIME
    PF_MAX_TIME=$left
    pf_probe "https://$KLYRO_REGISTRY/v2/$1/manifests/$2" "$3" -I -H "Accept: $PF_IMAGE_ACCEPT"
    pf_image_rec "$@"
    PF_MAX_TIME=15
}

# Records the line for the HEAD pf_image_check just made, with its arguments.
pf_image_rec() {
    case "$P_CODE" in
        200) pf_rec PASS "Image $1:$2" "tag on $KLYRO_REGISTRY (HTTP 200; its platforms are not checked), $4$5" ;;
        404) pf_rec FAIL "Image $1:$2" "not found on $KLYRO_REGISTRY (HTTP 404), $4$5" \
            "send this report to Klyro: the registry does not serve this image" ;;
        *) pf_registry_fail "Image $1:$2" "HEAD the image manifest" "$3" "$5" ;;
    esac
}

pf_platform() {
    PF_CHARTS=""
    PF_CHART_PATH="$(klyro_image_registry)"
    PF_CHART_PATH="${PF_CHART_PATH#"$KLYRO_REGISTRY"/}/charts"
    pf_section "Klyro platform"
    pf_rec INFO "Chart versions" "Exact chart versions come from Klyro Cloud at install time; this checks the latest published ones."
    pf_budget_ok || return 0
    pf_probe "https://$KLYRO_REGISTRY/v2/" host
    case "$P_CODE" in
        200|401) pf_rec PASS "Registry API" "$KLYRO_REGISTRY answers (HTTP $P_CODE), $(pf_net_route host "$KLYRO_REGISTRY")" ;;
        *) pf_registry_fail "Registry API" "GET /v2/" host ;;
    esac
    if pf_has researcher; then
        pf_budget_ok || return 0
        pf_chart_check klyro-edge "Researcher chart" ""
    fi
    if pf_has mc; then
        pf_budget_ok || return 0
        pf_chart_check mc "MC chart" "$MC_CHART_VERSION_OVERRIDE"
    fi
    pf_images
}

# host:port of PostgreSQL URL $1: its first host, port 5432 when it names none. Nothing
# when it names no host or a port that is not a number from 1 to 65535.
pf_pg_hostport() {
    local rest port
    rest=${1#*://}
    rest=${rest##*@}
    rest=${rest%%[/?]*}
    rest=${rest%%,*}
    case "$rest" in
        "") return 0 ;;
        \[*\]) rest="$rest:5432" ;;
        \[*\]:*|*:*) ;;
        *) rest="$rest:5432" ;;
    esac
    port=${rest##*:}
    case "$port" in
        ""|*[!0-9]*|0*|??????*) return 0 ;;
    esac
    [ "$port" -le 65535 ] && echo "$rest"
    return 0
}

# Value of query parameter $2 of URL $1, the last one when it repeats. Nothing when unset.
pf_pg_query() {
    case "$1" in
        *\?*) printf '%s\n' "${1#*\?}" | tr '&' '\n' | sed -n "s/^$2=//p" | tail -n 1 ;;
    esac
    return 0
}

# Whether $1 is a numeric address, as libpq's hostaddr needs: "ip" for dotted-quad IPv4 or
# IPv6, "name" when it holds a character no numeric address has (a host name), otherwise
# "unknown" (an encoded value, or a shorthand such as 127.1 that getaddrinfo may take).
pf_pg_hostaddr_kind() {
    case "$1" in
        *%*) echo unknown ;;
        *[!0-9A-Fa-fXx.:]*) echo name ;;
        *:*) echo ip ;;
        *)
            if printf '%s\n' "$1" | grep -Eq '^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$'; then
                echo ip
            else
                echo unknown
            fi
            ;;
    esac
}

# host:port that libpq connects to for URL $1 whose authority gives host:port $2 (maybe
# empty), once its query string's hostaddr, host and port override it. Nothing when an
# override is a list, a socket directory, an encoded value or a port that is not 1 to 65535.
pf_pg_libpq_hostport() {
    local h p
    h=$(pf_pg_query "$1" hostaddr)
    [ -n "$h" ] || h=$(pf_pg_query "$1" host)
    p=$(pf_pg_query "$1" port)
    if [ -z "$h" ]; then
        [ -n "$2" ] || return 0
        h=${2%:*}
        h=${h#\[}
        h=${h%\]}
    fi
    if [ -z "$p" ]; then
        if [ -n "$2" ]; then p=${2##*:}; else p=5432; fi
    fi
    case "$h" in
        ""|*%*|*/*|*,*|*\[*|*\]*|*" "*) return 0 ;;
        *:*) h="[$h]" ;;
    esac
    case "$p" in
        ""|*[!0-9]*|0*|??????*) return 0 ;;
    esac
    [ "$p" -le 65535 ] && echo "$h:$p"
    return 0
}

# The external MC database: its URL file, and a TCP connect to its host:port from this host
# (direct: the MC pods connect to it directly). No data is sent and no login is attempted.
pf_mc_database() {
    local url hp ha out tc rc src=""
    if [ "$MC_DB_MODE" != external ]; then
        pf_rec INFO "MC database" "bundled PostgreSQL in the cluster (nothing to check before install)"
        return 0
    fi
    if [ -z "$MC_DB_URL_FILE" ]; then
        if tty_available; then
            pf_rec WARN "MC DB URL file" "not checked: --mc-database external without --mc-database-url-file" \
                "pass --mc-database-url-file <file holding the postgres:// URL> so the preflight can check it"
        else
            pf_rec FAIL "MC DB URL file" "--mc-database external without --mc-database-url-file, and no terminal to ask for the URL" \
                "pass --mc-database-url-file <file holding the postgres:// URL>"
        fi
        return 0
    fi
    if [ ! -r "$MC_DB_URL_FILE" ]; then
        pf_rec FAIL "MC DB URL file" "cannot read $MC_DB_URL_FILE" "make $MC_DB_URL_FILE readable by the user running the installer"
        return 0
    fi
    url=$(tr -d '\r\n' < "$MC_DB_URL_FILE")
    case "$url" in
        postgres://*|postgresql://*) hp=$(pf_pg_hostport "$url") ;;
        *) hp="" ;;
    esac
    case "$url" in
        postgres://*\?*%*|postgresql://*\?*%*)
            if printf '%s\n' "${url#*\?}" | tr '&' '\n' | sed 's/=.*//' | grep -q '%'; then
                pf_rec INFO "MC DB URL file" "$MC_DB_URL_FILE: a URL whose query string has a percent-encoded parameter name, which libpq decodes and may read as its host or port; its reachability is not checked"
                return 0
            fi
            ;;
    esac
    ha=$(pf_pg_query "$url" hostaddr)
    if [ -n "$ha" ]; then
        case "$(pf_pg_hostaddr_kind "$ha")" in
            name)
                pf_rec FAIL "MC DB URL file" "$MC_DB_URL_FILE: hostaddr=$ha is not a numeric IP address; libpq accepts only one there, so the MC cannot connect" \
                    "put the database's IP address in hostaddr, or drop hostaddr and name the database host in host="
                return 0
                ;;
            unknown)
                pf_rec INFO "MC DB URL file" "$MC_DB_URL_FILE: hostaddr=$ha is not a plain IPv4 or IPv6 address; its reachability is not checked"
                return 0
                ;;
        esac
    fi
    case "$url" in
        postgres://*\?*host*=*|postgresql://*\?*host*=*|postgres://*\?*port=*|postgresql://*\?*port=*)
            if [ -n "$(pf_pg_query "$url" hostaddr)$(pf_pg_query "$url" host)$(pf_pg_query "$url" port)" ]; then
                hp=$(pf_pg_libpq_hostport "$url" "$hp")
                if [ -z "$hp" ]; then
                    pf_rec INFO "MC DB URL file" "$MC_DB_URL_FILE: a URL whose query string sets its host or port in a form this check does not read (a list, a socket directory, an encoded value or no host at all); its reachability is not checked"
                    return 0
                fi
                src=", host and port as libpq reads them (the query string overrides the URL's own)"
            fi
            ;;
    esac
    if [ -z "$hp" ]; then
        pf_rec FAIL "MC DB URL file" "$MC_DB_URL_FILE does not hold a postgres:// or postgresql:// URL with a host and a valid port" \
            "put one URL in it, e.g. postgres://user:password@host:5432/mc?sslmode=require"
        return 0
    fi
    pf_rec PASS "MC DB URL file" "$MC_DB_URL_FILE: a ${url%%://*}:// URL for $hp$src"
    pf_budget_ok || return 0
    out=$(LC_ALL=C curl -sS -g -o /dev/null -w 'PFTC:%{time_connect}' --connect-timeout 8 --max-time 15 \
        --noproxy '*' "telnet://$hp" 2>&1 </dev/null)
    rc=$?
    tc=$(printf '%s\n' "$out" | sed -n 's/.*PFTC:\([0-9.]*\).*/\1/p' | head -n 1)
    if awk -v t="${tc:-0}" 'BEGIN { exit !(t + 0 > 0) }'; then
        pf_rec PASS "MC DB reachable" "$hp accepts TCP connections from this host (no login attempted)"
        return 0
    fi
    case "$rc" in
        6) out="${hp%:*} does not resolve from this host" ;;
        7) out="$hp refused the connection" ;;
        28) out="$hp did not answer within 8s" ;;
        *) out="$hp cannot be reached: $(printf '%s\n' "$out" | grep '^curl: ' | head -n 1)" ;;
    esac
    pf_rec FAIL "MC DB reachable" "$out (TCP from this host)" \
        "allow TCP from this host and the cluster's pods to $hp, or fix the host and port in $MC_DB_URL_FILE"
}

# Succeeds when DNS name $1 of a certificate (possibly *.domain) covers host $2.
pf_name_covers() {
    case "$1" in
        "$2") return 0 ;;
        \*.*)
            case "$2" in
                *."${1#\*.}") [ "${2%."${1#\*.}"}" = "${2%%.*}" ] ;;
                *) return 1 ;;
            esac
            ;;
        *) return 1 ;;
    esac
}

# Succeeds when host $1 resolves from this host: getent, else curl (exit 6 is "could not
# resolve").
pf_resolves() {
    if command -v getent >/dev/null 2>&1; then
        getent hosts "$1" >/dev/null 2>&1
        return
    fi
    pf_curl host -sS -o /dev/null --noproxy '*' "https://$1/" >/dev/null 2>&1
    [ $? != 6 ]
}

# --scim-tls-secret: the Secret in the namespace, on a cluster that is already reachable.
pf_scim_secret() {
    local name="SCIM TLS Secret" out
    if [ "${PF_CLUSTER_UP:-}" != true ]; then
        pf_rec INFO "$name" "$MC_SCIM_TLS_SECRET not checked: no reachable cluster yet; create it in $NAMESPACE before the install deploys the MC"
        return 0
    fi
    pf_budget_ok || return 0
    if out=$(kubectl get secret "$MC_SCIM_TLS_SECRET" -n "$NAMESPACE" -o name --request-timeout=10s 2>&1 </dev/null); then
        pf_rec PASS "$name" "$MC_SCIM_TLS_SECRET is in $NAMESPACE"
        return 0
    fi
    case "$out" in
        *NotFound*)
            pf_rec WARN "$name" "$MC_SCIM_TLS_SECRET is not in $NAMESPACE: the SCIM Ingress has no certificate until it is" \
                "kubectl create secret tls $MC_SCIM_TLS_SECRET --cert=<file> --key=<file> -n $NAMESPACE, or pass --scim-tls-cert and --scim-tls-key instead" ;;
        *)
            pf_rec INFO "$name" "$MC_SCIM_TLS_SECRET not checked: $(printf '%s\n' "$out" | head -n 1)" ;;
    esac
}

# --scim-host: its DNS from this host, and --scim-tls-cert / --scim-tls-key when given.
pf_scim() {
    local host="$MC_SCIM_HOST" names name covered="" pub keypub
    if [ "$MC_NO_SCIM_INGRESS" = true ]; then
        pf_rec INFO SCIM "ingress off (--no-scim-ingress)"
        return 0
    fi
    if [ -z "$host" ]; then
        pf_rec INFO SCIM "through the Klyro relay (no --scim-host)"
        return 0
    fi
    pf_budget_ok || return 0
    if pf_resolves "$host"; then
        pf_rec PASS "SCIM host DNS" "$host resolves from this host"
    else
        pf_rec WARN "SCIM host DNS" "$host does not resolve from this host" \
            "create a DNS record for $host pointing at this cluster's ingress; your IGA must resolve and reach it"
    fi
    if [ -z "$MC_SCIM_TLS_CERT" ]; then
        [ -z "$MC_SCIM_TLS_SECRET" ] || pf_scim_secret
        return 0
    fi
    if [ ! -r "$MC_SCIM_TLS_CERT" ] || ! grep -q -- '-----BEGIN CERTIFICATE-----' "$MC_SCIM_TLS_CERT"; then
        pf_rec FAIL "SCIM TLS certificate" "$MC_SCIM_TLS_CERT is not a readable PEM certificate" \
            "pass --scim-tls-cert <PEM certificate for $host>"
        return 0
    fi
    if [ ! -r "$MC_SCIM_TLS_KEY" ] || ! grep -Eq -- '-----BEGIN ([A-Z]+ )?PRIVATE KEY-----' "$MC_SCIM_TLS_KEY"; then
        pf_rec FAIL "SCIM TLS key" "$MC_SCIM_TLS_KEY is not a readable PEM private key" \
            "pass --scim-tls-key <unencrypted PEM private key of the certificate>"
        return 0
    fi
    if ! command -v openssl >/dev/null 2>&1; then
        pf_rec INFO "SCIM TLS certificate" "$MC_SCIM_TLS_CERT and $MC_SCIM_TLS_KEY are PEM; host name and key match not checked (no openssl)"
        return 0
    fi
    names=$(openssl x509 -in "$MC_SCIM_TLS_CERT" -noout -text 2>/dev/null </dev/null | tr ',' '\n' \
        | sed -n 's/^[[:space:]]*DNS:\([^[:space:]]*\).*/\1/p')
    for name in $names; do
        pf_name_covers "$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')" "$host" && covered="$name"
    done
    if [ -n "$covered" ]; then
        pf_rec PASS "SCIM TLS certificate" "$MC_SCIM_TLS_CERT covers $host ($covered)"
    else
        pf_rec FAIL "SCIM TLS certificate" "$MC_SCIM_TLS_CERT does not cover $host (it names $(printf '%s' "${names:-no DNS names}" | tr '\n' ' ' | sed 's/ *$//; s/ /, /g'))" \
            "pass a certificate whose subjectAltName lists $host"
    fi
    pub=$(openssl x509 -in "$MC_SCIM_TLS_CERT" -noout -pubkey 2>/dev/null </dev/null)
    keypub=$(openssl pkey -in "$MC_SCIM_TLS_KEY" -pubout -passin pass: 2>/dev/null </dev/null)
    if [ -z "$keypub" ]; then
        pf_rec FAIL "SCIM TLS key" "openssl cannot read $MC_SCIM_TLS_KEY (it must be an unencrypted PEM key)" \
            "pass --scim-tls-key <unencrypted PEM private key of the certificate>"
    elif [ -n "$pub" ] && [ "$pub" = "$keypub" ]; then
        pf_rec PASS "SCIM TLS key" "$MC_SCIM_TLS_KEY matches the certificate"
    else
        pf_rec FAIL "SCIM TLS key" "$MC_SCIM_TLS_KEY does not match the certificate" \
            "pass the private key that belongs to $MC_SCIM_TLS_CERT"
    fi
}

pf_product() {
    pf_section "Product"
    case "$PRODUCT" in
        researcher) pf_rec INFO Components "Researcher" ;;
        mc) pf_rec INFO Components "MC" ;;
        both) pf_rec INFO Components "Researcher and MC" ;;
        none) pf_rec INFO Components "the klyro CLI only (no cluster checks)" ;;
        *) pf_rec INFO Components "Researcher and MC (default)" ;;
    esac
    pf_has mc || return 0
    pf_mc_database
    pf_scim
}

# The klyro CLI: its user, the host prep the install makes for it (INFO when missing),
# and squad/install.sh --check run as that user with KLYRO_SQUAD_ADMIN_PREP=1, its output
# kept under its line (status OUT) and its exit code 1 a FAIL.
pf_cli() {
    local f out rc line
    cli_wanted || return 0
    pf_section "klyro CLI"
    if ! resolve_cli_user; then
        pf_rec FAIL "CLI user" "$CLI_ERROR" "pass --cli-user <the user who will run klyro>, or leave cli out of --product"
        return 0
    fi
    if [ -n "$CLI_SKIP_REASON" ] && [ "${CLI_INSTALL:-}" = "on" ]; then
        pf_rec FAIL "CLI user" "--product asks for the klyro CLI, but $CLI_SKIP_REASON" \
            "run the installer with sudo as the user who will run klyro, or pass --cli-user <name>"
        return 0
    fi
    if [ -n "$CLI_SKIP_REASON" ]; then
        pf_rec WARN "CLI user" "$CLI_SKIP_REASON: the install skips the klyro CLI" \
            "run the installer with sudo as the user who will run klyro, or pass --cli-user <name> (--product researcher,mc leaves it out)"
        return 0
    fi
    pf_rec INFO "CLI user" "$CLI_USER (uid $CLI_UID, home $CLI_HOME, from $CLI_USER_SOURCE)"
    if [ "$(id -u)" -ne 0 ] && [ "${CLI_INSTALL:-}" = "on" ]; then
        pf_rec FAIL "Install as root" "--product names cli, and the install sets up the klyro CLI only when it runs as root" \
            "rerun the preflight with sudo, the way you will run the install"
    elif [ "$(id -u)" -ne 0 ]; then
        pf_rec INFO "Install as root" "the install sets up the klyro CLI only when it runs as root: run it with sudo"
    fi
    if fapolicyd_active; then
        f=$(cli_fapolicyd_file)
        if [ ! -d "$FAPOLICYD_RULES_DIR" ] && [ "${PF_NOROOT:-}" != "true" ]; then
            pf_rec WARN "fapolicyd (CLI)" "active, but $FAPOLICYD_RULES_DIR does not exist: the installer cannot allow $CLI_HOME/bin/, .local/bin/ and .klyro/" \
                "add the rules of $f to /etc/fapolicyd/fapolicyd.rules before its deny rules, then restart fapolicyd"
        elif [ "${PF_NOROOT:-}" != "true" ] && [ -z "$(cli_fapolicyd_missing)" ]; then
            pf_rec PASS "fapolicyd (CLI)" "$f allows $CLI_HOME/bin/, .local/bin/ and .klyro/"
        else
            pf_rec INFO "fapolicyd (CLI)" "set up by the installer: $f allows $CLI_HOME/bin/, .local/bin/ and .klyro/, then fapolicyd reloads"
        fi
    fi
    if cli_has_subids "$SUBUID_FILE" && cli_has_subids "$SUBGID_FILE"; then
        pf_rec PASS "Subordinate IDs" "$CLI_USER has a range in $SUBUID_FILE and $SUBGID_FILE"
    else
        pf_rec INFO "Subordinate IDs" "set up by the installer: usermod --add-subuids/--add-subgids $(cli_subid_range) $CLI_USER"
    fi
    if cli_lingers && [ -d "$(cli_runtime_dir)" ]; then
        pf_rec PASS "Linger" "on, $(cli_runtime_dir) exists"
    else
        pf_rec INFO "Linger" "set up by the installer: loginctl enable-linger $CLI_USER ($(cli_runtime_dir))"
    fi
    pf_budget_ok || return 0
    if [ "$CLI_USER" != "$(id -un)" ] && [ "$(id -u)" -ne 0 ] && [ "${AS_ROOT_SUDO:-}" != "true" ]; then
        pf_rec WARN "squad --check" "not run: running it as $CLI_USER needs root" "run the preflight as root or with sudo"
        return 0
    fi
    if ! out=$(fetch_squad_installer --connect-timeout 8 --max-time "$PF_MAX_TIME" 2>&1) || [ -z "$out" ]; then
        pf_rec FAIL "squad --check" "could not download $(squad_installer_url), or it is empty" \
            "this host must reach https://$KLYRO_CDN${PROXY_URL:+ through the proxy} (Network section)"
        return 0
    fi
    rc=0
    out=$(cli_run_squad "$out" KLYRO_SQUAD_ADMIN_PREP=1 bash -s -- --check 2>&1 </dev/null) || rc=$?
    case "$rc" in
        0) pf_rec PASS "squad --check" "ready ($(squad_installer_url) --check as $CLI_USER)" ;;
        1) pf_rec FAIL "squad --check" "not ready: see its FAIL lines below" \
            "fix what they and its admin asks say, or leave cli out of --product" ;;
        *) pf_rec FAIL "squad --check" "exited $rc ($(squad_installer_url) --check as $CLI_USER)" \
            "run it as $CLI_USER to see why, or leave cli out of --product" ;;
    esac
    out=$(printf '%s\n' "$out" | tr -d '\037')
    while IFS= read -r line; do
        case "$line" in *[![:space:]]*) pf_rec OUT "squad --check" "$line" ;; esac
    done <<PF_EOF
$out
PF_EOF
}

main_preflight() {
    local step steps
    set +e
    PF_BUDGET_S="${PF_BUDGET:-150}"
    case "$PF_BUDGET_S" in ""|*[!0-9]*) PF_BUDGET_S=150 ;; esac
    PF_DEADLINE=$(( $(date +%s) + PF_BUDGET_S ))
    trap pf_interrupted INT
    pf_section "Inputs"
    pf_check_token
    steps="pf_machine pf_network pf_tls pf_bedrock pf_platform pf_product pf_cli"
    [ "$PRODUCT" != "none" ] || steps="pf_product pf_cli"
    for step in $steps; do
        pf_budget_ok || break
        "$step"
    done
    pf_budget_ok
    trap - INT
    pf_report
    pf_finish
}

main() {
    is_local=false
    is_reinstall=false
    with_temporal=false
    bootstrap_cluster=false
    USE_HELM_CONTROLLER=false
    KLYRO_ENV="${KLYRO_ENV:-}"
    INSTALL_TOKEN=""
    CUSTOM_API_ENDPOINT=""
    CUSTOM_GRPC_ENDPOINT=""
    PRODUCT="${KLYRO_PRODUCT:-}"
    PRODUCT_DEFAULTED=""
    MC_DB_MODE=""
    MC_DB_URL_FILE=""
    MC_DB_URL=""
    MC_CHART_VERSION_OVERRIDE=""
    MC_SCIM_HOST=""
    MC_SCIM_INGRESS_CLASS=""
    MC_SCIM_TLS_SECRET=""
    MC_SCIM_TLS_CERT=""
    MC_SCIM_TLS_KEY=""
    MC_NO_SCIM_INGRESS=""
    MC_SCIM_STATE=""
    MC_CREDENTIAL_STORE_FLAG=""
    MC_CREDENTIAL_STORE=""
    SCIM_FIREWALL_FIX=""
    POD_FIREWALL_FIX=""
    HOST_PREP_CHANGES=""
    FAPOLICYD_RELOAD_PENDING=""
    CLI_INSTALL=""
    PRODUCT_LABEL=""
    CLI_USER_FLAG=""
    CLI_USER=""
    CLI_SKIP_REASON=""
    CLI_SUMMARY=""
    PROXY_URL=""
    PROXY_AUTO=""
    NO_PROXY_EXTRA=""
    NO_PROXY_VALUE=""
    CA_FILE=""
    EXTRA_CA_RECOVERED=""
    CHART_REPO=""
    K3S_DATA_DIR=""
    skip_disk_check=false
    PREFLIGHT=false
    BEDROCK_REGION="us-east-1"

    while [ $# -gt 0 ]; do
        case "$1" in
            --help|-h|help)
                usage
                ;;
            --local|--local-dev)
                is_local=true
                shift
                ;;
            --reinstall)
                is_reinstall=true
                shift
                ;;
            --preflight)
                PREFLIGHT=true
                shift
                ;;
            --with-temporal)
                with_temporal=true
                shift
                ;;
            --bootstrap|--with-k3s)
                bootstrap_cluster=true
                shift
                ;;
            --data-dir)
                case "${2:-}" in
                    *[[:space:]]*)
                        log_error "--data-dir cannot contain whitespace: the k3s installer word-splits INSTALL_K3S_EXEC"
                        exit 1
                        ;;
                    /*) K3S_DATA_DIR="$2" ;;
                    *)
                        log_error "--data-dir requires an absolute path"
                        exit 1
                        ;;
                esac
                shift 2
                ;;
            --skip-disk-check)
                skip_disk_check=true
                shift
                ;;
            --no-scim-ingress)
                MC_NO_SCIM_INGRESS=true
                shift
                ;;
            --no-credential-store)
                [ "$MC_CREDENTIAL_STORE_FLAG" = "on" ] && MC_CREDENTIAL_STORE_FLAG=conflict || MC_CREDENTIAL_STORE_FLAG=off
                shift
                ;;
            --credential-store)
                [ "$MC_CREDENTIAL_STORE_FLAG" = "off" ] && MC_CREDENTIAL_STORE_FLAG=conflict || MC_CREDENTIAL_STORE_FLAG=on
                shift
                ;;
            --env)
                case "${2:-}" in
                    ""|--*)
                        log_error "--env requires a value: dev, staging, or production"
                        exit 1
                        ;;
                esac
                KLYRO_ENV="$2"
                shift 2
                ;;
            --api-endpoint|--api_endpoint)
                CUSTOM_API_ENDPOINT="$2"
                shift 2
                ;;
            --grpc-endpoint|--grpc_endpoint)
                CUSTOM_GRPC_ENDPOINT="$2"
                shift 2
                ;;
            --product|--mc-database|--mc-database-url-file|--mc-chart-version|--proxy|--no-proxy|--ca-file|--chart-repo|\
            --scim-host|--scim-ingress-class|--scim-tls-secret|--scim-tls-cert|--scim-tls-key|--bedrock-region|--cli-user)
                case "${2:-}" in
                    ""|--*)
                        log_error "$1 requires a value (see --help)"
                        exit 1
                        ;;
                esac
                case "$1" in
                    --product) PRODUCT="$2" ;;
                    --mc-database) MC_DB_MODE="$2" ;;
                    --mc-database-url-file) MC_DB_URL_FILE="$2" ;;
                    --mc-chart-version) MC_CHART_VERSION_OVERRIDE="$2" ;;
                    --proxy) PROXY_URL="$2" ;;
                    --no-proxy) NO_PROXY_EXTRA=$(printf '%s' "$2" | tr -d ' ') ;;
                    --ca-file) CA_FILE="$2" ;;
                    --chart-repo) CHART_REPO="$2" ;;
                    --scim-host) MC_SCIM_HOST="$2" ;;
                    --scim-ingress-class) MC_SCIM_INGRESS_CLASS="$2" ;;
                    --scim-tls-secret) MC_SCIM_TLS_SECRET="$2" ;;
                    --scim-tls-cert) MC_SCIM_TLS_CERT="$2" ;;
                    --scim-tls-key) MC_SCIM_TLS_KEY="$2" ;;
                    --bedrock-region) BEDROCK_REGION="$2" ;;
                    --cli-user) CLI_USER_FLAG="$2" ;;
                esac
                shift 2
                ;;
            *)
                if [ -z "$INSTALL_TOKEN" ]; then
                    INSTALL_TOKEN="$1"
                fi
                shift
                ;;
        esac
    done

    if [ "$is_local" != "true" ] && [ "$is_reinstall" != "true" ]; then
        detect_env_proxy
    fi
    if [ -n "$NO_PROXY_EXTRA" ] && [ -z "$PROXY_URL" ]; then
        log_error "--no-proxy needs --proxy"
        exit 1
    fi
    validate_egress_settings

    if [ -n "$K3S_DATA_DIR" ] && [ "$bootstrap_cluster" != "true" ]; then
        log_error "--data-dir needs --bootstrap: it sets where the k3s that --bootstrap installs keeps its data"
        exit 1
    fi

    if [ "$PREFLIGHT" = "true" ]; then
        if [ "$is_local" = "true" ]; then
            log_error "--preflight cannot be combined with --local"
            exit 2
        fi
        if [ "$is_reinstall" = "true" ]; then
            log_error "--preflight cannot be combined with --reinstall"
            exit 2
        fi
    fi

    # Apply environment-specific URL defaults
    PF_AUTH_ENDPOINT_ENV="${AUTH_ENDPOINT:-}"
    apply_env_defaults
    check_product_flags

    [ "$PREFLIGHT" = "true" ] && main_preflight

    if [ "$PRODUCT" = "none" ]; then
        main_cli_only
        exit 0
    fi

    if [ "$is_reinstall" = "true" ]; then
        main_reinstall
        exit 0
    fi

    if [ -z "$INSTALL_TOKEN" ]; then
        log_error "Missing install token"
        echo ""
        usage
        exit 1
    fi

    export CUSTOM_API_ENDPOINT
    export CUSTOM_GRPC_ENDPOINT
    export with_temporal

    if [ "$is_local" = "true" ]; then
        main_local "$INSTALL_TOKEN"
    else
        main_production "$INSTALL_TOKEN"
    fi
}

main "$@"
