{{- $globalSecretName := printf "%s" (tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecret "context" $)) $) }}
apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ template "keycloak.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    app.kubernetes.io/component: keycloak
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  serviceName: {{ printf "%s-headless" (include "keycloak.fullname" .) | trunc 63 | trimSuffix "-" }}
  updateStrategy:
    {{- include "common.tplvalues.render" (dict "value" .Values.updateStrategy "context" $ ) | nindent 4 }}
  selector:
    matchLabels: {{ include "common.labels.matchLabels" . | nindent 6 }}
      app.kubernetes.io/component: keycloak
  template:
    metadata:
      annotations:
        checksum/configmap-env-vars: {{ include (print $.Template.BasePath "/configmap-env-vars.yaml") . | sha256sum }}
        {{- if and (not .Values.auth.existingSecret) (not .Values.auth.existingSecretPerPassword) }}
        checksum/secrets: {{ include (print $.Template.BasePath "/secrets.yaml") . | sha256sum }}
        {{- end }}
        {{- if (include "keycloak.createConfigmap" .) }}
        checksum/configuration: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        {{- end }}
        {{- if .Values.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
      labels: {{- include "common.labels.standard" . | nindent 8 }}
        app.kubernetes.io/component: keycloak
        {{- if .Values.podLabels }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podLabels "context" $) | nindent 8 }}
        {{- end }}
    spec:
      serviceAccountName: {{ template "keycloak.serviceAccountName" . }}
      {{- include "keycloak.imagePullSecrets" . | nindent 6 }}
      {{- if .Values.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.affinity }}
      affinity: {{- include "common.tplvalues.render" ( dict "value" .Values.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAffinityPreset "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAntiAffinityPreset "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" ( dict "value" .Values.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName }}
      {{- end }}
      {{- if .Values.podSecurityContext.enabled }}
      securityContext: {{- omit .Values.podSecurityContext "enabled" | toYaml | nindent 8 }}
      {{- end }}
      {{- if .Values.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if or .Values.initContainers .Values.auth.tls.enabled }}
      initContainers:
        {{- if .Values.auth.tls.enabled }}
        {{- $fullname := include "keycloak.fullname" . }}
        - name: init-certs
          image: {{ include "keycloak.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.containerSecurityContext.enabled }}
          securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }}
          {{- end }}
          command:
          - /bin/bash
          - -ec
          - |-
            ID="${MY_POD_NAME#"{{ $fullname }}-"}"
            {{- if or .Values.auth.tls.autoGenerated .Values.auth.tls.usePem }}
            if [[ -f "/certs/keycloak-${ID}.key" ]] && [[ -f "/certs/keycloak-${ID}.crt" ]] && [[ -f "/certs/ca.crt" ]]; then
              openssl pkcs12 -export -in "/certs/keycloak-${ID}.crt" \
                  -passout pass:"${KEYCLOAK_TLS_KEYSTORE_PASSWORD}" \
                  -inkey "/certs/keycloak-${ID}.key" \
                  -out "/tmp/keystore.p12"
              keytool -importkeystore -srckeystore "/tmp/keystore.p12" \
                  -srcstoretype PKCS12 \
                  -srcstorepass "${KEYCLOAK_TLS_KEYSTORE_PASSWORD}" \
                  -deststorepass "${KEYCLOAK_TLS_KEYSTORE_PASSWORD}" \
                  -destkeystore "/opt/bitnami/keycloak/certs/keycloak.keystore.jks"
              rm "/tmp/keystore.p12"
              keytool -import -file "/certs/ca.crt" \
                      -keystore "/opt/bitnami/keycloak/certs/keycloak.truststore.jks" \
                      -storepass "${KEYCLOAK_TLS_TRUSTSTORE_PASSWORD}" \
                      -noprompt
            else
                echo "Couldn't find the expected PEM certificates! They are mandatory when encryption via TLS is enabled."
                exit 1
            fi
            {{- else if and .Values.auth.tls.truststoreFilename .Values.auth.tls.keystoreFilename }}
            if [[ -f {{ printf "/certs/%s" .Values.auth.tls.truststoreFilename | quote }} ]] && [[ -f {{ printf "/certs/%s" .Values.auth.tls.keystoreFilename | quote }} ]]; then
                cp {{ printf "/certs/%s" .Values.auth.tls.truststoreFilename | quote }} "/opt/bitnami/keycloak/certs/keycloak.truststore.jks"
                cp {{ printf "/certs/%s" .Values.auth.tls.keystoreFilename | quote }} "/opt/bitnami/keycloak/certs/keycloak.keystore.jks"
            else
                echo "Couldn't find the expected Java Key Stores (JKS) files! They are mandatory when encryption via TLS is enabled."
                exit 1
            fi
            {{- else }}
            if [[ -f "/certs/keycloak.truststore.jks" ]] && [[ -f "/certs/keycloak-${ID}.keystore.jks" ]]; then
                cp "/certs/keycloak.truststore.jks" "/opt/bitnami/keycloak/certs/keycloak.truststore.jks"
                cp "/certs/keycloak-${ID}.keystore.jks" "/opt/bitnami/keycloak/certs/keycloak.keystore.jks"
            else
                echo "Couldn't find the expected Java Key Stores (JKS) files! They are mandatory when encryption via TLS is enabled."
                exit 1
            fi
            {{- end }}
          env:
            - name: MY_POD_NAME
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.name
            {{- if or .Values.auth.tls.keystorePassword .Values.auth.existingSecretPerPassword .Values.auth.tls.autoGenerated }}
            - name: KEYCLOAK_TLS_KEYSTORE_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.tlsKeystorePassword "context" $)) $ }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "tlsKeystorePassword") }}
                {{- else }}
                  name: {{ $globalSecretName }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecret "key" "tls-keystore-password") }}
                {{- end }}
            {{- end }}
            {{- if or .Values.auth.tls.truststorePassword .Values.auth.existingSecretPerPassword .Values.auth.tls.autoGenerated }}
            - name: KEYCLOAK_TLS_TRUSTSTORE_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.tlsTruststorePassword "context" $)) $ }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "tlsKeystorePassword") }}
                {{- else }}
                  name: {{ $globalSecretName }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecret "key" "tls-truestore-password") }}
                {{- end }}
            {{- end }}
          {{- if .Values.auth.tls.resources }}
          resources: {{- toYaml .Values.auth.tls.resources | nindent 12 }}
          {{- end }}
          volumeMounts:
          - name: certificates
            mountPath: /certs
          - name: shared-certs
            mountPath: /opt/bitnami/keycloak/certs
        {{- end }}
        {{- if .Values.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }}
        {{- end }}
      {{- end }}
      containers:
        - name: keycloak
          image: {{ template "keycloak.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.containerSecurityContext.enabled }}
          securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.command "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }}
          {{- else if .Values.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.args "context" $) | nindent 12 }}
          {{- end }}
          env:
            - name: KUBERNETES_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" .Values.image.debug | quote }}
            - name: KEYCLOAK_ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.adminPassword "context" $)) $ }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "adminPassword") }}
                {{- else }}
                  name: {{ $globalSecretName }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecret "key" "admin-password") }}
                {{- end }}
            - name: KEYCLOAK_MANAGEMENT_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.managementPassword "context" $)) $ }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "managementPassword") }}
                {{- else }}
                  name: {{ $globalSecretName }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecret "key" "management-password") }}
                {{- end }}
            - name: KEYCLOAK_DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.databasePassword "context" $)) $ }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "databasePassword") }}
                {{- else }}
                  name: {{ include "keycloak.databaseSecretName" . }}
                  key: {{ include "keycloak.databaseSecretKey" . }}
                {{- end }}
            {{- if .Values.auth.tls.enabled }}
            {{- if or .Values.auth.tls.keystorePassword .Values.auth.existingSecretPerPassword }}
            - name: KEYCLOAK_TLS_KEYSTORE_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.tlsKeystorePassword "context" $) $) }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "tlsKeystorePassword") }}
                {{- else }}
                  name: {{ $globalSecretName }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecret "key" "tls-keystore-password") }}
                {{- end }}
            {{- end }}
            {{- if or .Values.auth.tls.truststorePassword .Values.auth.existingSecretPerPassword }}
            - name: KEYCLOAK_TLS_TRUSTSTORE_PASSWORD
              valueFrom:
                secretKeyRef:
                {{- if .Values.auth.existingSecretPerPassword }}
                  name: {{ tpl (include "common.secrets.name" (dict "existingSecret" .Values.auth.existingSecretPerPassword.tlsTruststorePassword "context" $) $) }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecretPerPassword "key" "tlsKeystorePassword") }}
                {{- else }}
                  name: {{ $globalSecretName }}
                  key: {{ include "common.secrets.key" (dict "existingSecret" .Values.auth.existingSecret "key" "tls-truestore-password") }}
                {{- end }}
            {{- end }}
            {{- end }}
            {{- if .Values.extraStartupArgs }}
            - name: KEYCLOAK_EXTRA_ARGS
              value: {{ .Values.extraStartupArgs | quote }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            - configMapRef:
                name: {{ printf "%s-env-vars" (include "keycloak.fullname" .) }}
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsSecret "context" $) }}
            {{- end }}
            {{- if and .Values.externalDatabase.existingSecret (not .Values.postgresql.enabled) }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.externalDatabase.existingSecret "context" $) }}
            {{- end }}
          {{- if .Values.resources }}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          {{- end }}
          ports:
            - name: http
              containerPort: {{ .Values.containerPorts.http }}
              protocol: TCP
            - name: https
              containerPort: {{ .Values.containerPorts.https }}
              protocol: TCP
            - name: http-management
              containerPort: {{ .Values.containerPorts.management }}
              protocol: TCP
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.startupProbe.enabled }}
          startupProbe: {{- omit .Values.startupProbe "enabled" | toYaml | nindent 12 }}
            httpGet:
              path: /
              port: http
          {{- else if .Values.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customStartupProbe "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.livenessProbe.enabled }}
          livenessProbe: {{- omit .Values.livenessProbe "enabled" | toYaml | nindent 12 }}
            httpGet:
              path: /
              port: http
          {{- else if .Values.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customLivenessProbe "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.readinessProbe.enabled }}
          readinessProbe: {{- omit .Values.readinessProbe "enabled" | toYaml | nindent 12 }}
            httpGet:
              path: /realms/master
              port: http
          {{- else if .Values.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customReadinessProbe "context" $) | nindent 12 }}
          {{- end }}
          {{- end }}
          volumeMounts:
            {{- if or .Values.configuration .Values.existingConfigmap }}
            - name: keycloak-config
              mountPath: /bitnami/keycloak/conf/keycloak.conf
              subPath: keycloak.conf
            {{- end }}
            {{- if .Values.auth.tls.enabled }}
            - name: shared-certs
              mountPath: /opt/bitnami/keycloak/certs
              readOnly: true
            {{- end }}
            {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }}
            - name: custom-init-scripts
              mountPath: /docker-entrypoint-initdb.d
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
        {{- if .Values.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        {{- if or .Values.configuration .Values.existingConfigmap }}
        - name: keycloak-config
          configMap:
            name: {{ include "keycloak.configmapName" . }}
        {{- end }}
        {{- if .Values.auth.tls.enabled }}
        - name: certificates
          secret:
            secretName: {{ include "keycloak.tlsSecretName" . }}
            defaultMode: 420
        - name: shared-certs
          emptyDir: {}
        {{- end }}
        {{- if or .Values.initdbScriptsConfigMap .Values.initdbScripts }}
        - name: custom-init-scripts
          configMap:
            name: {{ include "keycloak.initdbScriptsCM" . }}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
