{{- /*
Auto-provision the Stalwart admin Secret (postmaster credential).

Same `lookup`-or-generate pattern as bp-stalwart-tenant 0.1.1 (#898) +
gitea-admin-secret (#830) + marketplace-api-secrets (#887). The random
ADMIN_PASSWORD survives helm upgrade / Flux re-reconciliation via the
Helm `lookup` against the existing in-namespace Secret — without this,
every reconcile would emit a NEW password, immediately invalidating
Stalwart's RocksDB-stored credential.

Per docs/INVIOLABLE-PRINCIPLES.md #10: the random value lives ONLY in
the Secret bytes — NEVER echoed, logged, or persisted elsewhere.

Steady state: lookup finds the existing Secret, decodes the value,
and re-encodes verbatim.
First install (or `helm template`): lookup returns nil; sprig's
`randAlphaNum` generates a fresh 32-character value.

helm.sh/resource-policy: keep — `helm uninstall` doesn't drop the
bytes; a re-install picks up the same value via lookup.
*/}}
{{- $a := .Values.admin -}}
{{- $auto := $a.autoProvision | default dict -}}
{{- $autoEnabled := dig "enabled" true $auto -}}
{{- if $autoEnabled -}}
{{- $secretName := $a.secretName -}}
{{- $namespace := .Release.Namespace -}}
{{- $existing := lookup "v1" "Secret" $namespace $secretName -}}
{{- $adminPassword := "" -}}
{{- if and $existing $existing.data (index $existing.data "ADMIN_PASSWORD") -}}
  {{- $adminPassword = index $existing.data "ADMIN_PASSWORD" | b64dec -}}
{{- else -}}
  {{- $adminPassword = randAlphaNum 32 -}}
{{- end -}}
apiVersion: v1
kind: Secret
metadata:
  name: {{ $secretName | quote }}
  namespace: {{ $namespace | quote }}
  labels:
    {{- include "bp-stalwart-sovereign.labels" . | nindent 4 }}
    catalyst.openova.io/component: stalwart-sovereign-admin
  annotations:
    helm.sh/resource-policy: keep
type: Opaque
data:
  ADMIN_PASSWORD: {{ $adminPassword | b64enc | quote }}
{{- end }}
