{{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-credentials" .Release.Name) }}
{{- $passwords := dict }}

{{- with (index $existingSecret "data") }}
  {{- range $k, $v := . }}
    {{- $_ := set $passwords $k (b64dec $v) }}
  {{- end }}
{{- end }}

{{- $usersWithRoot := .Values.users }}
{{- if not (and .Values.users.root .Values.users.root.password) }}
  {{- $_ := set $usersWithRoot "root" dict }}
{{- end }}

{{- range $user, $u := $usersWithRoot }}
  {{- if $u.password }}
    {{- $_ := set $passwords $user $u.password }}
  {{- else if not (index $passwords $user) }}
    {{- $_ := set $passwords $user (randAlphaNum 16) }}
  {{- end }}
{{- end }}

---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Release.Name }}-credentials
stringData:
  {{- range $name, $u := $usersWithRoot }}
  {{ $name }}: {{ index $passwords $name }}
  {{- end }}
