apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ template "common.names.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    {{- 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:
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" . | nindent 6 }}
  serviceName: {{ printf "%s-headless" (include "common.names.fullname" .) | trunc 63 | trimSuffix "-" }}
  updateStrategy:
    type: {{ .Values.updateStrategy.type }}
    {{- if (eq "Recreate" .Values.updateStrategy.type) }}
    rollingUpdate: null
    {{- end }}
  template:
    metadata:
      {{- if .Values.podAnnotations }}
      annotations: {{- include "common.tplvalues.render" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }}
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
      {{- end }}
      labels: {{- include "common.labels.matchLabels" . | nindent 8 }}
        {{- if .Values.podLabels }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podLabels "context" $) | nindent 8 }}
        {{- end }}
    spec:
      {{- include "mariadb-galera.imagePullSecrets" . | nindent 6 }}
      {{- if .Values.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName | quote }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
      {{- end }}
      serviceAccountName: {{ template "mariadb-galera.serviceAccountName" . }}
      {{- 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.podSecurityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.podSecurityContext.fsGroup }}
        runAsUser: {{ .Values.podSecurityContext.runAsUser }}
      {{- end }}
      {{- if .Values.initContainers }}
      initContainers: {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }}
      {{- end }}
      containers:
        - name: "mariadb-galera"
          image: {{ template "mariadb-galera.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.containerSecurityContext.enabled }}
          securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }}
          {{- end }}
          {{- if .Values.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" ( dict "value" .Values.lifecycleHooks "context" $ ) | 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 }}
          {{- else }}
          command:
            - bash
            - -ec
            - |
                {{- if .Values.galera.bootstrap.forceBootstrap }}
                {{- $fullname := include "common.names.fullname" . }}
                {{- $bootstrapFromNode := int .Values.galera.bootstrap.bootstrapFromNode }}
                # Bootstrap from the indicated node
                NODE_ID="${MY_POD_NAME#"{{ $fullname }}-"}"
                if [[ "$NODE_ID" -eq "{{ $bootstrapFromNode }}" ]]; then
                    export MARIADB_GALERA_CLUSTER_BOOTSTRAP=yes
                    export MARIADB_GALERA_FORCE_SAFETOBOOTSTRAP={{ ternary "yes" "no" .Values.galera.bootstrap.forceSafeToBootstrap }}
                else
                    export MARIADB_GALERA_CLUSTER_BOOTSTRAP=no
                fi
                {{- end }}
                exec /opt/bitnami/scripts/mariadb-galera/entrypoint.sh /opt/bitnami/scripts/mariadb-galera/run.sh
          {{- 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: MY_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: MARIADB_DEFAULT_PORT_NUMBER
              value: {{ .Values.containerPorts.mysql | quote }}
            - name: MARIADB_GALERA_CLUSTER_NAME
              value: {{ .Values.galera.name | quote }}
            {{- $fullName := include "common.names.fullname" . }}
            {{- $releaseName := include "common.names.namespace" . }}
            {{- $clusterDomain := .Values.clusterDomain }}
            {{- $initialCluster := list }}
            {{- range $e, $i := until (int .Values.replicaCount) }}
            {{- $initialCluster = append $initialCluster (printf "%s-%d.%s-headless.%s.svc.%s" $fullName $i $fullName $releaseName $clusterDomain) }}
            {{- end }}
            - name: MARIADB_GALERA_CLUSTER_ADDRESS
              value: {{ printf "gcomm://%s" (join "," $initialCluster) | quote }}
            - name: MARIADB_ROOT_USER
              value: {{ .Values.rootUser.user | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: MARIADB_ROOT_PASSWORD_FILE
              value: {{ default "/opt/bitnami/mariadb/secrets/mariadb-root-password" .Values.customPasswordFiles.root | quote }}
            {{- else }}
            - name: MARIADB_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "mariadb-galera.secretName" . }}
                  key: mariadb-root-password
            {{- end }}
            {{- if .Values.db.user }}
            - name: MARIADB_USER
              value: {{ .Values.db.user | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: MARIADB_PASSWORD_FILE
              value: {{ default "/opt/bitnami/mariadb/secrets/mariadb-password" .Values.customPasswordFiles.user | quote }}
            {{- else }}
            - name: MARIADB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "mariadb-galera.secretName" . }}
                  key: mariadb-password
            {{- end }}
            {{- end }}
            - name: MARIADB_DATABASE
              value: {{ .Values.db.name | quote }}
            - name: MARIADB_GALERA_MARIABACKUP_USER
              value: {{ .Values.galera.mariabackup.user | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: MARIADB_GALERA_MARIABACKUP_PASSWORD_FILE
              value: {{ default "/opt/bitnami/mariadb/secrets/mariadb-galera-mariabackup-password" .Values.customPasswordFiles.mariabackup | quote }}
            {{- else }}
            - name: MARIADB_GALERA_MARIABACKUP_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "mariadb-galera.secretName" . }}
                  key: mariadb-galera-mariabackup-password
            {{- end }}
            - name: MARIADB_ENABLE_LDAP
              value: {{ ternary "yes" "no" .Values.ldap.enabled | quote }}
            {{- if .Values.ldap.enabled }}
            - name: LDAP_URI
              value: {{ .Values.ldap.uri }}
            - name: LDAP_BASE
              value: {{ .Values.ldap.base }}
            - name: LDAP_BIND_DN
              value: {{ .Values.ldap.binddn }}
            - name: LDAP_BIND_PASSWORD
              valueFrom:
                secretKeyRef:
                  {{- if .Values.existingSecret }}
                  name: {{ .Values.existingSecret }}
                  {{- else }}
                  name: {{ template "common.names.fullname" . }}
                  {{- end }}
                  key: ldap-bindpw
            - name: LDAP_NSS_INITGROUPS_IGNOREUSERS
              value: {{ .Values.ldap.nss_initgroups_ignoreusers | quote }}
            {{- if .Values.ldap.bslookup }}
            - name: LDAP_BASE_LOOKUP
              value: {{ .Values.ldap.bslookup }}
            {{- end }}
            {{- if .Values.ldap.scope }}
            - name: LDAP_SCOPE
              value: {{ .Values.ldap.scope }}
            {{- end }}
            {{- if .Values.ldap.filter }}
            - name: LDAP_SEARCH_FILTER
              value: {{ .Values.ldap.filter }}
            {{- end }}
            {{- if .Values.ldap.map }}
            - name: LDAP_SEARCH_MAP
              value: {{ .Values.ldap.map }}
            {{- end }}
            {{- if .Values.ldap.tls_reqcert }}
            - name: LDAP_TLS_REQCERT
              value: {{ .Values.ldap.tls_reqcert }}
            {{- end }}
            {{- end }}
            {{- if .Values.extraFlags }}
            - name: MARIADB_EXTRA_FLAGS
              value: {{ .Values.extraFlags | quote }}
            {{- end }}
            - name: MARIADB_ENABLE_TLS
              value: {{ ternary "yes" "no" .Values.tls.enabled | quote }}
            {{- if .Values.tls.enabled }}
            - name:  MARIADB_TLS_CERT_FILE
              value: {{ template "mariadb-galera.tlsCert" . }}
            - name:  MARIADB_TLS_KEY_FILE
              value: {{ template "mariadb-galera.tlsCertKey" . }}
            - name:  MARIADB_TLS_CA_FILE
              value: {{ template "mariadb-galera.tlsCACert" . }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          {{- if or .Values.extraEnvVarsCM .Values.extraEnvVarsSecret }}
          envFrom:
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ .Values.extraEnvVarsCM }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ .Values.extraEnvVarsSecret }}
            {{- end }}
          {{- end }}
          ports:
            - name: mysql
              containerPort: {{ .Values.containerPorts.mysql }}
            - name: galera
              containerPort: {{ .Values.containerPorts.galera }}
            - name: ist
              containerPort: {{ .Values.containerPorts.ist }}
            - name: sst
              containerPort: {{ .Values.containerPorts.sst }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.livenessProbe.enabled }}
          livenessProbe:
            exec:
              command:
                - bash
                - -ec
                - |
                  password_aux="${MARIADB_ROOT_PASSWORD:-}"
                  if [[ -f "${MARIADB_ROOT_PASSWORD_FILE:-}" ]]; then
                      password_aux=$(cat "$MARIADB_ROOT_PASSWORD_FILE")
                  fi
                  exec mysql -u"${MARIADB_ROOT_USER}" -p"${password_aux}" -e "select * from mysql.wsrep_cluster_members;"
            initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.livenessProbe.successThreshold }}
            failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.readinessProbe.enabled }}
          readinessProbe:
            exec:
              command:
                - bash
                - -ec
                - |
                  {{- if or (.Files.Glob "files/docker-entrypoint-initdb.d/*.{sh,sql,sql.gz}") .Values.initdbScriptsConfigMap .Values.initdbScripts }}
                  # If the init scripts don't get executed there can be race conditions with the Galera bootstrap
                  if [[ ! -f "{{ .Values.persistence.mountPath }}/.user_scripts_initialized" ]]; then
                      echo "Init scripts still not executed. Skipping check"
                      exit 1
                  fi
                  {{- end }}
                  password_aux="${MARIADB_ROOT_PASSWORD:-}"
                  if [[ -f "${MARIADB_ROOT_PASSWORD_FILE:-}" ]]; then
                      password_aux=$(cat "$MARIADB_ROOT_PASSWORD_FILE")
                  fi
                  exec mysqladmin status -u"${MARIADB_ROOT_USER}" -p"${password_aux}"
            initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.readinessProbe.successThreshold }}
            failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.startupProbe.enabled }}
          startupProbe:
            exec:
              command:
                - bash
                - -ec
                - |
                  {{- if or (.Files.Glob "files/docker-entrypoint-initdb.d/*.{sh,sql,sql.gz}") .Values.initdbScriptsConfigMap .Values.initdbScripts }}
                  # If the init scripts don't get executed there can be race conditions with the Galera bootstrap
                  if [[ ! -f "{{ .Values.persistence.mountPath }}/.user_scripts_initialized" ]]; then
                      echo "Init scripts still not executed. Skipping check"
                      exit 1
                  fi
                  {{- end }}
                  password_aux="${MARIADB_ROOT_PASSWORD:-}"
                  if [[ -f "${MARIADB_ROOT_PASSWORD_FILE:-}" ]]; then
                      password_aux=$(cat "$MARIADB_ROOT_PASSWORD_FILE")
                  fi
                  exec mysqladmin status -u"${MARIADB_ROOT_USER}" -p"${password_aux}"
            initialDelaySeconds: {{ .Values.startupProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.startupProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.startupProbe.timeoutSeconds }}
            successThreshold: {{ .Values.startupProbe.successThreshold }}
            failureThreshold: {{ .Values.startupProbe.failureThreshold }}
          {{- end }}
          {{- end }}
          {{- if .Values.resources }}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: previous-boot
              mountPath: /opt/bitnami/mariadb/.bootstrap
            - name: data
              mountPath: {{ .Values.persistence.mountPath }}
              {{- if .Values.persistence.subPath }}
              subPath: {{ .Values.persistence.subPath }}
              {{- end }}
            {{- if or (.Files.Glob "files/docker-entrypoint-initdb.d/*.{sh,sql,sql.gz}") .Values.initdbScriptsConfigMap .Values.initdbScripts }}
            - name: custom-init-scripts
              mountPath: /docker-entrypoint-initdb.d
            {{- end }}
            {{- if or (.Files.Glob "files/my.cnf") .Values.mariadbConfiguration .Values.configurationConfigMap }}
            - name: mariadb-galera-config
              mountPath: /bitnami/conf/my.cnf
              subPath: my.cnf
            {{- end }}
            {{- if .Values.tls.enabled }}
            - name: mariadb-galera-certificates
              mountPath: /bitnami/mariadb/certs/
              readOnly: true
            {{- end }}
            {{- if and .Values.usePasswordFiles (not .Values.customPasswordFiles) }}
            - name: mariadb-galera-credentials
              mountPath: /opt/bitnami/mariadb/secrets/
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- toYaml .Values.extraVolumeMounts | nindent 12 }}
            {{- end }}
        {{- if .Values.metrics.enabled }}
        - name: metrics
          image: {{ template "mariadb-galera.metrics.image" . }}
          imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }}
          {{- if .Values.metrics.containerSecurityContext.enabled }}
          securityContext: {{- omit .Values.metrics.containerSecurityContext "enabled" | toYaml | nindent 12 }}
          {{- end }}
          env:
            - name: MARIADB_METRICS_EXTRA_FLAGS
              value: {{ default "" (join " " .Values.metrics.extraFlags) | quote }}
            - name: MARIADB_ROOT_USER
              value: {{ .Values.rootUser.user | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: MARIADB_ROOT_PASSWORD_FILE
              value: {{ default "/opt/bitnami/mysqld-exporter/secrets/mariadb-root-password" .Values.customPasswordFiles.root }}
            {{- else }}
            - name: MARIADB_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ template "mariadb-galera.secretName" . }}
                  key: mariadb-root-password
            {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else }}
          command:
            - /bin/bash
            - -ec
            - |
              password_aux="${MARIADB_ROOT_PASSWORD:-}"
              if [[ -f "${MARIADB_ROOT_PASSWORD_FILE:-}" ]]; then
                  password_aux=$(cat "$MARIADB_ROOT_PASSWORD_FILE")
              fi
              DATA_SOURCE_NAME="${MARIADB_ROOT_USER}:${password_aux}@(localhost:3306)/" /bin/mysqld_exporter $MARIADB_METRICS_EXTRA_FLAGS
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }}
          {{- end }}
          ports:
            - name: metrics
              containerPort: 9104
          {{- if not .Values.diagnosticMode.enabled }}
          livenessProbe:
            httpGet:
              path: /
              port: metrics
            initialDelaySeconds: 30
            timeoutSeconds: 5
          readinessProbe:
            httpGet:
              path: /
              port: metrics
            initialDelaySeconds: 5
            timeoutSeconds: 1
          {{- end }}
          {{- if .Values.metrics.resources }}
          resources: {{- toYaml .Values.metrics.resources | nindent 12 }}
          {{- end }}
          {{- if and .Values.usePasswordFiles (not .Values.customPasswordFiles) }}
          volumeMounts:
            - name: mariadb-galera-credentials
              mountPath: /opt/bitnami/mysqld-exporter/secrets/
          {{- end }}
        {{- end }}
        {{- if .Values.sidecars }}
        {{- include "common.tplvalues.render" (dict "value" .Values.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: previous-boot
          emptyDir: {}
        {{- if and .Values.usePasswordFiles (not .Values.customPasswordFiles) }}
        - name: mariadb-galera-credentials
          secret:
            secretName: {{ template "mariadb-galera.secretName" . }}
            items:
              - key: mariadb-root-password
                path: mariadb-root-password
              - key: mariadb-password
                path: mariadb-password
              - key: mariadb-galera-mariabackup-password
                path: mariadb-galera-mariabackup-password
        {{- end }}
        {{- if .Values.tls.enabled }}
        - name: mariadb-galera-certificates
          secret:
            secretName: {{ include "mariadb-galera.tlsSecretName" . }}
            defaultMode: 256
        {{- end }}
        {{- if or (.Files.Glob "files/my.cnf") .Values.mariadbConfiguration .Values.configurationConfigMap }}
        - name: mariadb-galera-config
          configMap:
            name: {{ template "mariadb-galera.configurationCM" . }}
        {{- end }}
        {{- if or (.Files.Glob "files/docker-entrypoint-initdb.d/*.{sh,sql,sql.gz}") .Values.initdbScriptsConfigMap .Values.initdbScripts }}
        - name: custom-init-scripts
          configMap:
            name: {{ template "mariadb-galera.initdbScriptsCM" . }}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- toYaml .Values.extraVolumes | nindent 8 }}
        {{- end }}
{{- if and .Values.persistence.enabled .Values.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            claimName: {{ .Values.persistence.existingClaim }}
{{- else if not .Values.persistence.enabled }}
        - name: data
          emptyDir: {}
{{- else if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
  volumeClaimTemplates:
    - metadata:
        name: data
        labels: {{- include "common.labels.matchLabels" . | nindent 10 }}
          app.kubernetes.io/managed-by: {{ .Release.Service }}
          {{- if .Values.persistence.labels }}
          {{- include "common.tplvalues.render" (dict "value" .Values.persistence.labels "context" $) | nindent 10 }}
          {{- end }}
        {{- if .Values.persistence.annotations }}
        annotations:
        {{- include "common.tplvalues.render" (dict "value" .Values.persistence.annotations "context" $) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistence.size | quote }}
        {{- if .Values.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.selector "context" $) | nindent 10 }}
        {{- end -}}
        {{- include "common.storage.class" (dict "persistence" .Values.persistence "global" .Values.global) | nindent 8 }}
{{- end }}
