{{- /*
Step 06 — helmrepository-patches.

For each HelmRepository in .Values.helmRepositories.names, patches
spec.url from oci://ghcr.io/openova-io/<name> to
oci://harbor.<sov-fqdn>/openova-io/<name>.

Image phase: post.
*/ -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: cutover-step-06-helmrepository-patches
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "bp-self-sovereign-cutover.labels" . | nindent 4 }}
    app.kubernetes.io/component: cutover-step
    bp.openova.io/cutover-order: "6"
    bp.openova.io/cutover-mode: "job"
data:
  stepName: helmrepository-patches
  helmrepository-names.txt: |
    {{- range .Values.helmRepositories.names }}
    {{ . }}
    {{- end }}
  podSpec: |
    serviceAccountName: {{ include "bp-self-sovereign-cutover.serviceAccountName" . }}
    restartPolicy: Never
    activeDeadlineSeconds: {{ .Values.stepTimeouts.helmRepositoryPatchesSeconds }}
    containers:
      - name: helmrepository-patches
        image: {{ include "bp-self-sovereign-cutover.image" (dict "repository" .Values.images.kubectl.repository "tag" .Values.images.kubectl.tag "cutoverPhase" "post" "Values" .Values) }}
        imagePullPolicy: IfNotPresent
        env:
          - name: HELMREPO_NAMESPACE
            value: {{ .Values.helmRepositories.namespace | quote }}
          - name: UPSTREAM_PREFIX
            value: {{ .Values.helmRepositories.upstreamPrefix | quote }}
          - name: HARBOR_PUBLIC_URL
            value: {{ .Values.sovereign.harborPublicURL | quote }}
        volumeMounts:
          - name: helmrepository-list
            mountPath: /work
            readOnly: true
        command: ["/bin/sh", "-c"]
        args:
          - |
            set -eu
            harbor_host=$(printf '%s' "${HARBOR_PUBLIC_URL}" | sed -E 's,^https?://,,; s,/$,,')
            local_prefix="oci://${harbor_host}/openova-io"

            echo "[helmrepository-patches] upstream=${UPSTREAM_PREFIX} -> local=${local_prefix}"

            ok=0
            skip=0
            fail=0
            while IFS= read -r line; do
              name=$(printf '%s' "${line}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
              [ -z "${name}" ] && continue

              cur_url=$(kubectl get helmrepository "${name}" \
                -n "${HELMREPO_NAMESPACE}" \
                -o jsonpath='{.spec.url}' 2>/dev/null || echo "")

              if [ -z "${cur_url}" ]; then
                echo "[helmrepository-patches] SKIP ${name} (not found)"
                skip=$((skip+1))
                continue
              fi

              new_url=$(printf '%s' "${cur_url}" | sed -e "s,${UPSTREAM_PREFIX},${local_prefix},")
              if [ "${new_url}" = "${cur_url}" ]; then
                echo "[helmrepository-patches] SKIP ${name} (already pivoted or non-default URL)"
                skip=$((skip+1))
                continue
              fi

              patch=$(printf '{"spec":{"url":"%s"}}' "${new_url}")
              if kubectl patch helmrepository "${name}" \
                  -n "${HELMREPO_NAMESPACE}" \
                  --type=merge --patch "${patch}" >/dev/null; then
                kubectl annotate --overwrite helmrepository "${name}" \
                  -n "${HELMREPO_NAMESPACE}" \
                  "reconcile.fluxcd.io/requestedAt=$(date +%s)" >/dev/null
                echo "[helmrepository-patches] OK ${name} -> ${new_url}"
                ok=$((ok+1))
              else
                echo "[helmrepository-patches] FAIL ${name}"
                fail=$((fail+1))
              fi
            done < /work/helmrepository-names.txt

            echo "[helmrepository-patches] ok=${ok} skip=${skip} fail=${fail}"
            [ "${fail}" -eq 0 ]
        resources:
          requests: { cpu: 50m, memory: 64Mi }
          limits:   { memory: 256Mi }
        securityContext:
          runAsNonRoot: true
          runAsUser: 1001
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop: ["ALL"]
    volumes:
      - name: helmrepository-list
        configMap:
          name: cutover-step-06-helmrepository-patches
          items:
            - key: helmrepository-names.txt
              path: helmrepository-names.txt
