apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ template "master.fullname" . }}
  labels:
    app: "{{ template "mariadb.name" . }}"
    chart: "{{ template "mariadb.chart" . }}"
    component: "master"
    release: {{ .Release.Name | quote }}
    heritage: {{ .Release.Service | quote }}
spec:
  selector:
    matchLabels:
      release: "{{ .Release.Name }}"
      component: "master"
      app: "{{ template "mariadb.name" . }}"
  serviceName: "{{ template "master.fullname" . }}"
  replicas: 1
  updateStrategy:
    type: {{ .Values.master.updateStrategy.type }}
    {{- if (eq "Recreate" .Values.master.updateStrategy.type) }}
    rollingUpdate: null
    {{- end }}
  template:
    metadata:
      {{- if .Values.master.annotations }}
      annotations:
        {{- range $key, $value := .Values.master.annotations }}
        {{ $key }}: '{{ $value }}'
        {{- end }}
      {{- end }}
      labels:
        app: "{{ template "mariadb.name" . }}"
        component: "master"
        release: "{{ .Release.Name }}"
        chart: "{{ template "mariadb.chart" . }}"
    spec:
      {{- if .Values.schedulerName }}
      schedulerName: "{{ .Values.schedulerName }}"
      {{- end }}
      serviceAccountName: "{{ template "mariadb.serviceAccountName" . }}"
      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsUser: {{ .Values.securityContext.runAsUser }}
      {{- end }}
      {{- if eq .Values.master.antiAffinity "hard" }}
      affinity:
      {{- with .Values.master.affinity  }}
{{ toYaml . | indent 8 }}
      {{- end }}
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - topologyKey: "kubernetes.io/hostname"
              labelSelector:
                matchLabels:
                  app: "{{ template "mariadb.name" . }}"
                  release: "{{ .Release.Name }}"
      {{- else if eq .Values.master.antiAffinity "soft" }}
      affinity:
      {{- with .Values.master.affinity  }}
{{ toYaml . | indent 8 }}
      {{- end }}
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            podAffinityTerm:
              topologyKey: kubernetes.io/hostname
              labelSelector:
                matchLabels:
                  app: "{{ template "mariadb.name" . }}"
                  release: "{{ .Release.Name }}"
      {{- else}}
      {{- with .Values.master.affinity }}
      affinity:
{{ toYaml . | indent 8 }}
      {{- end }}
      {{- end }}
      {{- if .Values.master.nodeSelector }}
      nodeSelector:
        {{ toYaml .Values.master.nodeSelector | nindent 8 }}
      {{- end -}}
      {{- with .Values.master.tolerations }}
      tolerations:
{{ toYaml . | indent 8 }}
      {{- end }}
{{- include "mariadb.imagePullSecrets" . | indent 6 }}
      initContainers:
      {{- if .Values.master.extraInitContainers }}
{{ tpl .Values.master.extraInitContainers . | indent 6}}
      {{- end }}
      {{- if and .Values.volumePermissions.enabled .Values.master.persistence.enabled }}
      - name: volume-permissions
        image: {{ template "mariadb.volumePermissions.image" . }}
        imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }}
        command: ["chown", "-R", "{{ .Values.securityContext.runAsUser }}:{{ .Values.securityContext.fsGroup }}", "{{ .Values.master.persistence.mountPath }}"]
        securityContext:
          runAsUser: 0
        resources: {{ toYaml .Values.volumePermissions.resources | nindent 10 }}
        volumeMounts:
        - name: data
          mountPath: {{ .Values.master.persistence.mountPath }}
      {{- end }}
      containers:
      - name: "mariadb"
        image: {{ template "mariadb.image" . }}
        imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
        env:
        {{- if .Values.image.debug}}
        - name: BITNAMI_DEBUG
          value: "true"
        {{- end }}
        {{- if .Values.master.extraFlags }}
        - name: MARIADB_EXTRA_FLAGS
          value: "{{ .Values.master.extraFlags }}"
        {{- end }}
        - name: MARIADB_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
            {{- if .Values.existingSecret }}
              name: {{ .Values.existingSecret }}
            {{- else }}
              name: {{ template "mariadb.fullname" . }}
            {{- end }}
              key: mariadb-root-password
        {{- if .Values.db.user }}
        - name: MARIADB_USER
          value: "{{ .Values.db.user }}"
        - name: MARIADB_PASSWORD
          valueFrom:
            secretKeyRef:
            {{- if .Values.existingSecret }}
              name: {{ .Values.existingSecret }}
            {{- else }}
              name: {{ template "mariadb.fullname" . }}
            {{- end }}
              key: mariadb-password
        {{- end }}
        - name: MARIADB_DATABASE
          value: "{{ .Values.db.name }}"
        {{- if .Values.replication.enabled }}
        - name: MARIADB_REPLICATION_MODE
          value: "master"
        - name: MARIADB_REPLICATION_USER
          value: "{{ .Values.replication.user }}"
        - name: MARIADB_REPLICATION_PASSWORD
          valueFrom:
            secretKeyRef:
            {{- if .Values.existingSecret }}
              name: {{ .Values.existingSecret }}
            {{- else }}
              name: {{ template "mariadb.fullname" . }}
            {{- end }}
              key: mariadb-replication-password
        {{- end }}
        ports:
        - name: mysql
          containerPort: 3306
        {{- if .Values.master.livenessProbe.enabled }}
        livenessProbe:
          exec:
            command: ["sh", "-c", "exec mysqladmin status -uroot -p$MARIADB_ROOT_PASSWORD"]
          initialDelaySeconds: {{ .Values.master.livenessProbe.initialDelaySeconds }}
          periodSeconds: {{ .Values.master.livenessProbe.periodSeconds }}
          timeoutSeconds: {{ .Values.master.livenessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.master.livenessProbe.successThreshold }}
          failureThreshold: {{ .Values.master.livenessProbe.failureThreshold }}
        {{- end }}
        {{- if .Values.master.readinessProbe.enabled }}
        readinessProbe:
          exec:
            command: ["sh", "-c", "exec mysqladmin status -uroot -p$MARIADB_ROOT_PASSWORD"]
          initialDelaySeconds: {{ .Values.master.readinessProbe.initialDelaySeconds }}
          periodSeconds: {{ .Values.master.readinessProbe.periodSeconds }}
          timeoutSeconds: {{ .Values.master.readinessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.master.readinessProbe.successThreshold }}
          failureThreshold: {{ .Values.master.readinessProbe.failureThreshold }}
        {{- end }}
        resources:
{{ toYaml .Values.master.resources | indent 10 }}
        volumeMounts:
        - name: data
          mountPath: {{ .Values.master.persistence.mountPath }}
          {{- if .Values.master.persistence.subPath }}
          subPath: {{ .Values.master.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 .Values.master.config }}
        - name: config
          mountPath: /opt/bitnami/mariadb/conf/my.cnf
          subPath: my.cnf
       {{- end }}
{{- if .Values.metrics.enabled }}
      - name: metrics
        image: {{ template "mariadb.metrics.image" . }}
        imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }}
        env:
        - name: MARIADB_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
            {{- if .Values.existingSecret }}
              name: {{ .Values.existingSecret }}
            {{- else }}
              name: {{ template "mariadb.fullname" . }}
            {{- end }}
              key: mariadb-root-password
        command: [ 'sh', '-c', 'DATA_SOURCE_NAME="root:$MARIADB_ROOT_PASSWORD@(localhost:3306)/" /bin/mysqld_exporter' ]
        ports:
        - name: metrics
          containerPort: 9104
        livenessProbe:
          httpGet:
            path: /metrics
            port: metrics
          initialDelaySeconds: 15
          timeoutSeconds: 5
        readinessProbe:
          httpGet:
            path: /metrics
            port: metrics
          initialDelaySeconds: 5
          timeoutSeconds: 1
        resources:
{{ toYaml .Values.metrics.resources | indent 10 }}
{{- end }}
      volumes:
        {{- if .Values.master.config }}
        - name: config
          configMap:
            name: {{ template "master.fullname" . }}
        {{- 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.initdbScriptsCM" . }}
        {{- end }}
{{- if and .Values.master.persistence.enabled .Values.master.persistence.existingClaim }}
        - name: data
          persistentVolumeClaim:
            claimName: {{ .Values.master.persistence.existingClaim }}
{{- else if not .Values.master.persistence.enabled }}
        - name: data
          emptyDir: {}
{{- else if and .Values.master.persistence.enabled (not .Values.master.persistence.existingClaim) }}
  volumeClaimTemplates:
    - metadata:
        name: data
        labels:
          app: "{{ template "mariadb.name" . }}"
          component: "master"
          release: {{ .Release.Name | quote }}
          heritage: {{ .Release.Service | quote }}
      spec:
        accessModes:
        {{- range .Values.master.persistence.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.master.persistence.size | quote }}
      {{- if .Values.master.persistence.storageClass }}
      {{- if (eq "-" .Values.master.persistence.storageClass) }}
        storageClassName: ""
      {{- else }}
        storageClassName: {{ .Values.master.persistence.storageClass | quote }}
      {{- end }}
      {{- end }}
{{- end }}
