#!/usr/bin/env bash

set -u

NAMESPACE="${1:-dapr-demo}"

section() {
  printf '\n## %s\n' "$1"
}

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    printf 'Required command not found: %s\n' "$1" >&2
    exit 1
  fi
}

require_command kubectl
require_command dapr

section "Client and cluster context"
kubectl config current-context
kubectl version
dapr --version

section "Dapr control plane"
dapr status --kubernetes

section "Dapr-enabled applications"
dapr list --kubernetes

section "mTLS status and certificate expiry"
dapr mtls --kubernetes
# dapr mtls expiry detects the Kubernetes installation automatically.
dapr mtls expiry

section "Dapr-enabled Deployments in namespace ${NAMESPACE}"
kubectl get deployments --namespace "$NAMESPACE" \
  --output go-template='{{range .items}}{{if index .spec.template.metadata.annotations "dapr.io/enabled"}}{{.metadata.name}}{{"\tapp-id="}}{{index .spec.template.metadata.annotations "dapr.io/app-id"}}{{"\n"}}{{end}}{{end}}'

section "Injected sidecar images in namespace ${NAMESPACE}"
kubectl get pods --namespace "$NAMESPACE" \
  --output go-template='{{range .items}}{{range .spec.containers}}{{if eq .name "daprd"}}{{$.metadata.name}}{{"\t"}}{{.image}}{{"\n"}}{{end}}{{end}}{{end}}'

section "Dapr custom resources"
for resource in components.dapr.io configurations.dapr.io resiliencies.dapr.io subscriptions.dapr.io; do
  printf '\n### %s\n' "$resource"
  kubectl get "$resource" --all-namespaces 2>/dev/null || printf 'Not installed or no access to list %s\n' "$resource"
done

section "Dapr system persistent volumes"
kubectl get persistentvolumeclaims --namespace dapr-system 2>/dev/null || \
  printf 'No PVCs found, dapr-system is absent, or access was denied.\n'

section "Recent warning events"
kubectl get events --all-namespaces \
  --field-selector type=Warning \
  --sort-by='.lastTimestamp' 2>/dev/null | tail -n 30 || true

printf '\nPreflight inventory complete. Save this output with the change record.\n'
