#!/bin/sh
# Migration 64 --> 65
# Convert PostgreSQL accounts to platform-minted credentials, first part.
#
# The converted postgres chart renders a CredentialTemplate per user, and
# each managed role reads its verifier from the template's account Secret,
# which cozystack-controller seeds with a random password only on a release
# marked for seeding. This hook runs before any component chart changes
# version and writes those Secrets, unowned, for every existing Postgres
# release from the passwords in <release>-credentials, so clients keep
# logging in at every point of the upgrade; the controller adopts them once
# the templates exist. A release whose every account got its Secret is
# marked for seeding, so users added later are seeded too.
#
# The second part is the cozystack-credentials-migration-64 Job, which waits
# per release for its chart to switch, then strips the plaintext and retires
# the source Secret. This hook creates that Job directly rather than rendering
# it from the platform chart: a chart-rendered Job has a fixed name and an
# image that changes every release, so the next platform upgrade cannot patch
# its immutable pod template, and helm-controller would wait on a Job that runs
# for up to 30 minutes and exits non-zero while any release is left out. A Job
# created here runs outside the platform HelmRelease, so it holds up no
# upgrade. It runs the image this hook runs as, read from its own pod. The Job
# is deleted and recreated rather than patched, so a hook that reruns on a
# newer image does not fault on the immutable pod template.
#
# The Job's ServiceAccount is bound to a least-privilege ClusterRole, not
# cluster-admin: finish needs only CRUD on Secrets, get/list/patch on
# HelmReleases, create on Events, and its state ConfigMap (pods/exec, which a
# later wave's MariaDB rotation needs, is not granted here). The ServiceAccount
# is owned by the Job, so the garbage collector removes it whenever the Job is
# (its TTL, a rerun, or by hand), on the success and the failure path alike, so
# no standing identity outlives the Job. A ClusterRoleBinding cannot be owned by
# a namespaced Job, so the binding is left; once the ServiceAccount is gone it
# grants to no subject that exists. On a conversion a stuck release leaves
# permanently failed, an operator clearing that release should delete the
# ClusterRoleBinding and ClusterRole by hand. While any release is left out,
# credentials-migrate labels its state ConfigMap credentials.cozystack.io/incomplete=true,
# which the CredentialsMigrationIncomplete alert fires on: the ConfigMap outlives
# the Job, so a release whose plaintext was never retired is seen until the
# conversion is finished, not only for the Job's TTL. To rerun it by hand, delete
# the Job and re-apply the manifest below.
#
# Fail-closed: migrations never re-run, so an error here stops the upgrade
# rather than stamping the version past a release that was not recorded.

set -euo pipefail

# shellcheck source=lib/cozystack-version.sh
. "$(dirname "$0")/lib/cozystack-version.sh"

NAMESPACE="${NAMESPACE:-cozy-system}"

# The converted postgres chart renders CredentialTemplates, whose CRD ships
# with cozystack-controller. That release can upgrade minutes after the tenant
# releases switch charts, and every render in between fails on the unknown
# kind, so apply the CRD baked into this image first, owned by the
# cozystack-controller release as its later upgrade expects to find it.
CRD_FILE="${CREDENTIAL_CRD_FILE:-/credential-crds/cozystack.io_credentialtemplates.yaml}"
kubectl apply --server-side --force-conflicts --filename "$CRD_FILE"
kubectl label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm --overwrite
kubectl annotate crd credentialtemplates.cozystack.io \
  meta.helm.sh/release-name=cozystack-controller \
  meta.helm.sh/release-namespace=cozy-system --overwrite
kubectl wait --for=condition=established crd/credentialtemplates.cozystack.io --timeout=60s

credentials-migrate seed \
  --migration 64 \
  --kind Postgres \
  --format scram-sha-256 \
  --accounts-path users \
  --refuse-flag createRole \
  --label 'cnpg.io/reload=true'

# The finish Job runs the same image as this hook, so a release and its
# conversion share the credentials-migrate build. Read it from this pod's own
# container by name rather than render it from values, which the hook does not
# carry, and rather than by position, which a webhook-injected container shifts.
image=$(kubectl get pod "$(hostname)" \
  --namespace "$NAMESPACE" \
  --output 'jsonpath={.spec.containers[?(@.name=="migration")].image}')
if [ -z "$image" ]; then
  echo "cannot read this pod's image to run the finish Job" >&2
  exit 1
fi

# Delete any Job left by an earlier run of this hook: its pod template is
# immutable, so a rerun on a newer image would fault on apply. finish recovers
# its progress from the state ConfigMap, so recreating the Job loses nothing.
# Delete the ServiceAccount with it: an earlier run may have left it owned by
# the Job just deleted, and the apply below does not touch ownerReferences, so
# without this the garbage collector could remove the re-applied ServiceAccount
# out from under the ownerReference patch. A fresh, owner-less ServiceAccount is
# never collected before the patch names the new Job.
kubectl delete job cozystack-credentials-migration-64 \
  --namespace "$NAMESPACE" \
  --ignore-not-found
kubectl delete serviceaccount cozystack-credentials-migration-64 \
  --namespace "$NAMESPACE" \
  --ignore-not-found

kubectl apply --filename - <<YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cozystack-credentials-migration-64
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "create", "patch", "delete"]
  - apiGroups: [""]
    resources: ["configmaps"]
    verbs: ["get", "create", "update"]
  - apiGroups: [""]
    resources: ["events"]
    verbs: ["create"]
  - apiGroups: ["helm.toolkit.fluxcd.io"]
    resources: ["helmreleases"]
    verbs: ["get", "list", "patch"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: cozystack-credentials-migration-64
  namespace: ${NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: cozystack-credentials-migration-64
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cozystack-credentials-migration-64
subjects:
  - kind: ServiceAccount
    name: cozystack-credentials-migration-64
    namespace: ${NAMESPACE}
---
apiVersion: batch/v1
kind: Job
metadata:
  name: cozystack-credentials-migration-64
  namespace: ${NAMESPACE}
spec:
  backoffLimit: 6
  ttlSecondsAfterFinished: 604800
  template:
    metadata:
      labels:
        policy.cozystack.io/allow-to-apiserver: "true"
    spec:
      serviceAccountName: cozystack-credentials-migration-64
      restartPolicy: OnFailure
      containers:
        - name: migration
          image: ${image}
          command:
            - credentials-migrate
            - finish
            - --migration=64
            - --kind=Postgres
            - --format=scram-sha-256
            - --accounts-path=users
            - --refuse-flag=createRole
            - --label=cnpg.io/reload=true
            - --timeout=30m
          env:
            - name: CREDENTIALS_MIGRATE_ACTOR
              value: system:serviceaccount:${NAMESPACE}:cozystack-credentials-migration-64
YAML

# Tie the ServiceAccount's lifetime to the Job: when the Job is deleted (its
# ttlSecondsAfterFinished, a rerun's delete above, or an operator by hand) the
# garbage collector removes the ServiceAccount, on the success and the failure
# path alike, so the least-privilege identity does not stand indefinitely after
# a release the conversion left out.
job_uid=$(kubectl get job cozystack-credentials-migration-64 \
  --namespace "$NAMESPACE" \
  --output 'jsonpath={.metadata.uid}')
if [ -z "$job_uid" ]; then
  echo "cannot read the finish Job's uid to own its ServiceAccount" >&2
  exit 1
fi
kubectl patch serviceaccount cozystack-credentials-migration-64 \
  --namespace "$NAMESPACE" \
  --type merge \
  --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-64\",\"uid\":\"${job_uid}\"}]}}"

stamp_cozystack_version 65
