{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if and .Values.passwordUpdateJob.enabled (include "postgresql.v1.createSecret" .) (not ( include "postgresql.v1.createPreviousSecret" . )) (not .Values.passwordUpdateJob.previousPasswords.existingSecret) }}
{{- $customUser := include "postgresql.v1.username" . }}
{{- $postgresPassword := (ternary (coalesce .Values.global.postgresql.auth.password .Values.auth.password .Values.global.postgresql.auth.postgresPassword .Values.auth.postgresPassword) (coalesce .Values.global.postgresql.auth.postgresPassword .Values.auth.postgresPassword) (or (empty $customUser) (eq $customUser "postgres"))) }}
{{- $password := coalesce .Values.global.postgresql.auth.password .Values.auth.password }}
{{- $replicationPassword := .Values.auth.replicationPassword }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ printf "%s-new-secret" (include "common.names.fullname" .) | trunc 63 | trimSuffix "-" }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: postgresql
  {{- $defaultAnnotations := dict "helm.sh/hook" "pre-upgrade" "helm.sh/hook-delete-policy" "hook-succeeded" }}
  {{- $annotations := include "common.tplvalues.merge" ( dict "values" ( list .Values.commonAnnotations $defaultAnnotations ) "context" . ) }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" $annotations "context" $ ) | nindent 4 }}
type: Opaque
data:
  {{- if .Values.auth.enablePostgresUser }}
  postgres-password: {{ required "The new postgres password is required!" $postgresPassword | b64enc | quote }}
  {{- end }}
  {{- if and (not (empty $customUser)) (ne $customUser "postgres") }}
  password: {{ required "The new user password is required!" $password | b64enc | quote }}
  {{- end }}
  {{- if or (eq .Values.architecture "replication") .Values.primary.standby.enabled }}
  replication-password: {{ required "The new replication password is required!" $replicationPassword | b64enc | quote }}
  {{- end }}
{{- end }}
