{{/*
# Copyright © 2018 Amdocs
# Copyright © 2018,2021 Bell Canada
# Copyright © 2019 Samsung Electronics
# Copyright © 2019-2020 Orange
# Copyright © 2020 Bitnami
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/}}

apiVersion: apps/v1
kind: StatefulSet
metadata: {{- include "common.resourceMetadata" . | nindent 2 }}
spec:
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  replicas: {{ .Values.replicaCount }}
  selector: {{- include "common.selectors" . | nindent 4 }}
  serviceName: {{ include "common.servicename" . }}-headless
  updateStrategy:
    type: {{ .Values.updateStrategy.type }}
    {{- if (eq "Recreate" .Values.updateStrategy.type) }}
    rollingUpdate: null
    {{- end }}
  template:
    metadata: {{- include "common.templateMetadata" . | nindent 6 }}
    spec:
      {{ include "common.podSecurityContext" . | indent 6  | trim }}
      initContainers:
        # we shouldn't need this but for unknown reason, it's fsGroup is not
        # applied
        - name: fix-permission
          command:
            - /bin/sh
          args:
            - -c
            - |
              chown -R {{ .Values.securityContext.user_id }}:{{ .Values.securityContext.group_id }} /data
              chown -R {{ .Values.securityContext.user_id }}:{{ .Values.securityContext.group_id }} /bootstrap/
              chown -R {{ .Values.securityContext.user_id }}:{{ .Values.securityContext.group_id }} /tmp/
              {{- if .Values.mariadbConfiguration }}
              cp /config/my.cnf /actual/my.cnf
              chown -R {{ .Values.securityContext.user_id }}:{{ .Values.securityContext.group_id }} /actual
              {{- end }}
          image: {{ include "repositoryGenerator.image.busybox" . }}
          imagePullPolicy: {{ .Values.global.pullPolicy | default .Values.pullPolicy }}
          securityContext:
            runAsUser: 0
          volumeMounts:
            - name: previous-boot
              mountPath: /bootstrap
            - name: mariadb-tmp-folder
              mountPath: /tmp
            - name: {{ include "common.fullname" . }}
              mountPath: /data
            {{- if .Values.mariadbConfiguration }}
            - name: mariadb-galera-starting-config
              mountPath: /config/my.cnf
              subPath: my.cnf
            - name: mariadb-galera-actual-config
              mountPath: /actual
            {{- end }}
      containers:
        - name: {{ include "common.name" . }}
          image: {{ include "repositoryGenerator.dockerHubRepository" . }}/{{ .Values.image }}
          imagePullPolicy: {{ .Values.global.pullPolicy | default .Values.pullPolicy | quote}}
          command:
            - bash
            - -ec
            - |
                {{- if (not (empty (.Values.galera.bootstrap.bootstrapFromNode | quote)))}}
                {{- $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 }}
                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.debug | quote }}
            - name: MARIADB_INIT_SLEEP_TIME
              value: {{ .Values.init_sleep_time | quote }}
            - name: MARIADB_GALERA_CLUSTER_NAME
              value: {{ .Values.galera.name | quote }}
            - name: MARIADB_GALERA_CLUSTER_ADDRESS
              value: "gcomm://{{ template "common.name" . }}-headless.{{ include "common.namespace" . }}.svc.{{ .Values.global.clusterDomain }}"
            # Bitnami init script don't behave well in dual stack env.
            # set it here as long as https://github.com/bitnami/charts/issues/4077 is not solved.
            - name: MARIADB_GALERA_NODE_ADDRESS
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: MARIADB_ROOT_USER
              value: {{ .Values.rootUser.user | quote }}
            - name: MARIADB_ROOT_PASSWORD
              {{- include "common.secret.envFromSecretFast" (dict "global" . "uid" (include "common.mariadb.secret.rootPassUID" .) "key" "password") | indent 14 }}
            - name: MARIADB_USER
              {{- include "common.secret.envFromSecretFast" (dict "global" . "uid" (include "common.mariadb.secret.userCredentialsUID" .) "key" "login") | indent 14 }}
            - name: MARIADB_PASSWORD
              {{- include "common.secret.envFromSecretFast" (dict "global" . "uid" (include "common.mariadb.secret.userCredentialsUID" .) "key" "password") | indent 14 }}
            - name: MARIADB_DATABASE
              value: {{ .Values.db.name | quote }}
            - name: MARIADB_GALERA_MARIABACKUP_USER
              {{- include "common.secret.envFromSecretFast" (dict "global" . "uid" (include "common.mariadb.secret.backupCredentialsUID" .) "key" "login") | indent 14 }}
            - name: MARIADB_GALERA_MARIABACKUP_PASSWORD
              {{- include "common.secret.envFromSecretFast" (dict "global" . "uid" (include "common.mariadb.secret.backupCredentialsUID" .) "key" "password") | indent 14 }}
            {{- if .Values.extraFlags }}
            - name: MARIADB_EXTRA_FLAGS
              value: {{ .Values.extraFlags | quote }}
            {{- end }}
          ports: {{ include "common.containerPorts" . | nindent 12  }}
          {{- if .Values.livenessProbe.enabled }}
          livenessProbe:
            exec:
              command:
                - sh
                - -ec
                - |
                  exec mysqladmin status -u$MARIADB_ROOT_USER -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:
                - sh
                - -ec
                - |
                  exec mysqladmin status -u$MARIADB_ROOT_USER -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.startupProbe.enabled }}
          startupProbe:
            exec:
              command:
                - sh
                - -ec
                - |
                  exec mysqladmin status -u$MARIADB_ROOT_USER -p$MARIADB_ROOT_PASSWORD
            initialDelaySeconds: {{ .Values.startupProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.startupProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.startupProbe.timeoutSeconds }}
            successThreshold: {{ .Values.startupProbe.successThreshold }}
            failureThreshold: {{ .Values.startupProbe.failureThreshold }}
          {{- end }}
          resources: {{ include "common.resources" . | nindent 12 }}
          volumeMounts:
            - name: previous-boot
              mountPath: /opt/bitnami/mariadb/.bootstrap
            - name: {{ include "common.fullname" . }}
              mountPath: /bitnami/mariadb
            - name: mariadb-tmp-folder
              mountPath: /opt/bitnami/mariadb/tmp
            {{- if .Values.mariadbConfiguration }}
            - name: mariadb-galera-actual-config
              mountPath: /opt/bitnami/mariadb/conf
            {{- end }}
        {{- if default false .Values.global.metrics.enabled }}
        - name: {{ include "common.name" . }}-metrics
          image: {{ include "repositoryGenerator.dockerHubRepository" . }}/{{ .Values.metrics.image }}
          imagePullPolicy: {{ .Values.global.pullPolicy | default .Values.metrics.pullPolicy | quote}}
          env:
            - name: MARIADB_METRICS_EXTRA_FLAGS
              value: {{ default "" (join " " .Values.metrics.extraFlags) | quote }}
            - name: MARIADB_ROOT_USER
              value: {{ .Values.rootUser.user | quote }}
            - name: MARIADB_ROOT_PASSWORD
              {{- include "common.secret.envFromSecretFast" (dict "global" . "uid" (include "common.mariadb.secret.rootPassUID" .) "key" "password") | indent 14}}
          command:
            - sh
            - -c
            - |
              DATA_SOURCE_NAME="$MARIADB_ROOT_USER:$MARIADB_ROOT_PASSWORD@(localhost:3306)/" /bin/mysqld_exporter $MARIADB_METRICS_EXTRA_FLAGS
          ports:
            - name: metrics
              containerPort: 9104
          livenessProbe:
            httpGet:
              path: /metrics
              port: metrics
            initialDelaySeconds: {{ .Values.metrics.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.metrics.livenessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.metrics.livenessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.metrics.livenessProbe.successThreshold }}
            failureThreshold: {{ .Values.metrics.livenessProbe.failureThreshold }}
          readinessProbe:
            httpGet:
              path: /metrics
              port: metrics
            initialDelaySeconds: {{ .Values.metrics.readinessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.metrics.readinessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.metrics.readinessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.metrics.readinessProbe.successThreshold }}
            failureThreshold: {{ .Values.metrics.readinessProbe.failureThreshold }}
          {{ include "common.containerSecurityContext" . | indent 10 | trim }}
          resources: {{- toYaml .Values.metrics.resources | nindent 12 }}
        {{- end }}
      imagePullSecrets:
        - name: {{ include "common.namespace" . }}-docker-registry-key
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName | quote }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
      {{- end }}
      serviceAccountName: {{ include "common.fullname" (dict "suffix" "read" "dot" . )}}
      {{- if .Values.affinity }}
      affinity: {{- include "common.tplValue" ( 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.tplValue" ( dict "value" .Values.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "common.tplValue" (dict "value" .Values.tolerations "context" .) | nindent 8 }}
      {{- end }}
      volumes:
        - name: previous-boot
          emptyDir: {}
        - name: mariadb-tmp-folder
          emptyDir: {}
        {{- if .Values.mariadbConfiguration  }}
        - name:  mariadb-galera-actual-config
          emptyDir: {}
        - name: mariadb-galera-starting-config
          configMap:
            name: {{ printf "%s-configuration" (include "common.fullname" .) }}
        {{- end }}
{{- if and .Values.persistence.enabled .Values.persistence.existingClaim }}
        - name: {{ include "common.fullname" . }}
          persistentVolumeClaim:
            claimName: {{ .Values.persistence.existingClaim }}
{{- else if not .Values.persistence.enabled }}
        - name: {{ include "common.fullname" . }}
          emptyDir: {}
{{- else if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
  volumeClaimTemplates:
    - {{ include "common.PVCTemplate" (dict "dot" . "suffix" "data" "persistenceInfos" .Values.persistence) | indent 6 | trim }}
{{- end }}