{{- if .Values.global.enable_basicAuth }}

{{- $ironicUsername := "" -}}
{{- $ironicPassword := "" -}}
{{- $ironicSecretName := "ironic-basic-auth" -}}

# Check if the secret is deployed and has a password
{{- $oldIronicSecret := lookup "v1" "Secret" .Release.Namespace $ironicSecretName }}
{{- if and $oldIronicSecret (index $oldIronicSecret.data "username") (index $oldIronicSecret.data "password") }}
{{- $ironicUsername = b64dec (index $oldIronicSecret.data "username" | toString) -}}
{{- $ironicPassword = b64dec (index $oldIronicSecret.data "password" | toString) -}}
# If not, check if a username and password are provided in values.yaml
{{- else if and (.Values.global.auth.ironicUsername) (.Values.global.auth.ironicPassword) }}
{{- $ironicUsername = .Values.global.auth.ironicUsername -}}
{{- $ironicPassword = .Values.global.auth.ironicPassword -}}
{{- else }}
# If no username and password are provided in values.yaml, generate new ones
{{- $ironicUsername = "ironic" -}}
{{- $ironicPassword = (randAlphaNum 20) -}}
{{- end }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ $ironicSecretName }}
type: Opaque
data:
  username: {{ $ironicUsername | b64enc }}
  password: {{ $ironicPassword | b64enc }}
  htpasswd: {{ b64enc (htpasswd $ironicUsername $ironicPassword) }}
  auth-config: |
  {{- printf "[ironic]\nauth_type=http_basic\nusername: %s\npassword: %s" $ironicUsername $ironicPassword | b64enc | nindent 4 }}

{{- end }}
