apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ template "mariadb-galera.fullname" . }}
  labels: {{- include "mariadb-galera.labels" . | nindent 4 }}
spec:
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels: {{- include "mariadb-galera.matchLabels" . | nindent 6 }}
  serviceName: {{ template "mariadb-galera.fullname" . }}
  updateStrategy:
    type: {{ .Values.updateStrategy.type }}
    {{- if (eq "Recreate" .Values.updateStrategy.type) }}
    rollingUpdate: null
    {{- end }}
  template:
    metadata:
      {{- if .Values.podAnnotations }}
      annotations: {{- include "mariadb-galera.tplValue" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }}
      {{- end }}
      labels: {{- include "mariadb-galera.labels" . | nindent 8 }}
    spec:
{{- include "mariadb-galera.imagePullSecrets" . | indent 6 }}
      {{- 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 "mariadb-galera.tplValue" (dict "value" .Values.affinity "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector: {{- include "mariadb-galera.tplValue" (dict "value" .Values.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "mariadb-galera.tplValue" (dict "value" .Values.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsUser: {{ .Values.securityContext.runAsUser }}
      {{- end }}
      {{- if .Values.extraInitContainers }}
      initContainers: {{- include "mariadb-galera.tplValue" (dict "value" .Values.extraInitContainers "context" $) | nindent 8 }}
      {{- end }}
      containers:
        - name: "mariadb-galera"
          image: {{ template "mariadb-galera.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          command:
            - bash
            - -ec
            - |
                {{- if (not (empty (.Values.galera.bootstrap.bootstrapFromNode | quote)))}}
                {{- $fullname := include "mariadb-galera.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 }}
                fi
                {{- end }}
                exec /opt/bitnami/scripts/mariadb-galera/entrypoint.sh /opt/bitnami/scripts/mariadb-galera/run.sh
          env:
            - name: MY_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" .Values.image.debug | quote }}
            - name: MARIADB_GALERA_CLUSTER_NAME
              value: {{ .Values.galera.name | quote }}
            - name: MARIADB_GALERA_CLUSTER_ADDRESS
              value: "gcomm://{{ template "mariadb-galera.fullname" . }}-headless.{{ .Release.Namespace }}.svc.{{ .Values.clusterDomain }}"
            - name: MARIADB_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  {{- if .Values.existingSecret }}
                  name: {{ .Values.existingSecret }}
                  {{- else }}
                  name: {{ template "mariadb-galera.fullname" . }}
                  {{- end }}
                  key: mariadb-root-password
            {{- if .Values.db.user }}
            - name: MARIADB_USER
              value: {{ .Values.db.user | quote }}
            - name: MARIADB_PASSWORD
              valueFrom:
                secretKeyRef:
                  {{- if .Values.existingSecret }}
                  name: {{ .Values.existingSecret }}
                  {{- else }}
                  name: {{ template "mariadb-galera.fullname" . }}
                  {{- end }}
                  key: mariadb-password
            {{- end }}
            - name: MARIADB_DATABASE
              value: {{ .Values.db.name | quote }}
            - name: MARIADB_GALERA_MARIABACKUP_USER
              value: {{ .Values.galera.mariabackup.user }}
            - name: MARIADB_GALERA_MARIABACKUP_PASSWORD
              valueFrom:
                secretKeyRef:
                  {{- if .Values.existingSecret }}
                  name: {{ .Values.existingSecret }}
                  {{- else }}
                  name: {{ template "mariadb-galera.fullname" . }}
                  {{- end }}
                  key: mariadb-galera-mariabackup-password
            - 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 "mariadb-galera.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.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 "mariadb-galera.tplValue" (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: 3306
            - name: galera
              containerPort: 4567
            - name: ist
              containerPort: 4568
            - name: sst
              containerPort: 4444
          {{- if .Values.livenessProbe.enabled }}
          livenessProbe:
            exec:
              command:
                - bash
                - -ec
                - |
                  exec mysqladmin status -uroot -p$MARIADB_ROOT_PASSWORD
            initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.livenessProbe.successThreshold }}
            failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.readinessProbe.enabled }}
          readinessProbe:
            exec:
              command:
                - bash
                - -ec
                - |
                  exec mysqladmin status -uroot -p$MARIADB_ROOT_PASSWORD
            initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.readinessProbe.successThreshold }}
            failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
          {{- 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: /opt/bitnami/mariadb/conf/my.cnf
              subPath: my.cnf
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- toYaml .Values.extraVolumeMounts | nindent 12 }}
            {{- end }}
            {{- if .Values.tls.enabled }}
            - name: mariadb-galera-certificates
              mountPath: /bitnami/mariadb/certs/
              readOnly: true
            {{- end }}
        {{- if .Values.metrics.enabled }}
        - name: metrics
          image: {{ template "mariadb-galera.metrics.image" . }}
          imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }}
          env:
            - name: MARIADB_METRICS_EXTRA_FLAGS
              value: {{ default "" (join " " .Values.metrics.extraFlags) | quote }}
            - name: MARIADB_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  {{- if .Values.existingSecret }}
                  name: {{ .Values.existingSecret }}
                  {{- else }}
                  name: {{ template "mariadb-galera.fullname" . }}
                  {{- end }}
                  key: mariadb-root-password
          command:
            - sh
            - -c
            - |
              DATA_SOURCE_NAME="root:$MARIADB_ROOT_PASSWORD@(localhost:3306)/" /bin/mysqld_exporter $MARIADB_METRICS_EXTRA_FLAGS
          ports:
            - name: metrics
              containerPort: 9104
          livenessProbe:
            httpGet:
              path: /metrics
              port: metrics
            initialDelaySeconds: 30
            timeoutSeconds: 5
          readinessProbe:
            httpGet:
              path: /metrics
              port: metrics
            initialDelaySeconds: 5
            timeoutSeconds: 1
          {{- if .Values.metrics.resources }}
          resources: {{- toYaml .Values.metrics.resources | nindent 12 }}
          {{- end }}
        {{- end }}
        {{- if .Values.extraContainers }}
        {{- include "mariadb-galera.tplValue" (dict "value" .Values.extraContainers "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: previous-boot
          emptyDir: {}
        {{- if .Values.tls.enabled }}
        - name: mariadb-galera-certificates
          secret:
            secretName: {{ required "A secret containing the certificates for the TLS traffic is required when TLS in enabled" .Values.tls.certificatesSecret }}
            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:
          app.kubernetes.io/name: {{ include "mariadb-galera.name" . }}
          app.kubernetes.io/instance: {{ .Release.Name }}
          app.kubernetes.io/managed-by: {{ .Release.Service }}
      spec:
        accessModes:
        {{- range .Values.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistence.size | quote }}
        {{ include "mariadb-galera.storageClass" . }}
        {{- if .Values.persistence.selector }}
        selector: {{- include "mariadb-galera.tplValue" (dict "value" .Values.persistence.selector "context" $) | nindent 10 }}
        {{- end -}}
{{- end }}
