# _helpers.tpl
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "mongodb-replicaset.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "mongodb-replicaset.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "mongodb-replicaset.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create the name for the admin secret.
*/}}
{{- define "mongodb-replicaset.adminSecret" -}}
    {{- if .Values.auth.existingAdminSecret -}}
        {{- .Values.auth.existingAdminSecret -}}
    {{- else -}}
        {{- template "mongodb-replicaset.fullname" . -}}-admin
    {{- end -}}
{{- end -}}

{{- define "mongodb-replicaset.metricsSecret" -}}
    {{- if .Values.auth.existingMetricsSecret -}}
        {{- .Values.auth.existingMetricsSecret -}}
    {{- else -}}
        {{- template "mongodb-replicaset.fullname" . -}}-metrics
    {{- end -}}
{{- end -}}


{{/*
Create the name for the key secret.
*/}}
{{- define "mongodb-replicaset.keySecret" -}}
    {{- if .Values.auth.existingKeySecret -}}
        {{- .Values.auth.existingKeySecret -}}
    {{- else -}}
        {{- template "mongodb-replicaset.fullname" . -}}-keyfile
    {{- end -}}
{{- end -}}

{{- define "mongodb-replicaset.connection-string" -}}
  {{- $string := "" -}}
  {{- if .Values.auth.enabled }}
   {{- $string = printf "mongodb://$METRICS_USER:$METRICS_PASSWORD@localhost:%s" (.Values.port|toString) -}}
  {{- else -}}
   {{- $string = printf "mongodb://localhost:%s" (.Values.port|toString) -}}
  {{- end -}}

  {{- if .Values.tls.enabled }}
  {{- printf "%s/?ssl=true&tlsCertificateKeyFile=/work-dir/mongo.pem&tlsCAFile=/ca/tls.crt" $string | quote -}}
  {{- else -}}
  {{- printf $string | quote -}}
  {{- end -}}
{{- end -}}

{{/*
Allow the release namespace to be overridden for multi-namespace deployments in combined charts.
*/}}
{{- define "mongodb-replicaset.namespace" -}}
  {{- if .Values.global -}}
    {{- if .Values.global.namespaceOverride -}}
      {{- .Values.global.namespaceOverride -}}
    {{- else -}}
      {{- .Release.Namespace -}}
    {{- end -}}
  {{- else -}}
    {{- .Release.Namespace -}}
  {{- end -}}    
{{- end -}}
 # mongodb-admin-secret.yaml
{{- if and (.Values.auth.enabled) (not .Values.auth.existingAdminSecret) -}}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
{{- if .Values.secretAnnotations }}
  annotations:
{{ toYaml .Values.secretAnnotations | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.adminSecret" . }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
type: Opaque
data:
  user: {{ .Values.auth.adminUser | b64enc }}
  password: {{ .Values.auth.adminPassword | b64enc }}
{{- end -}}
 # mongodb-ca-secret.yaml
{{- if .Values.tls.enabled -}}
apiVersion: v1
kind: Secret
type: kubernetes.io/tls
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}-ca
  namespace: {{ template "mongodb-replicaset.namespace" . }}
data:
  tls.key: {{ .Values.tls.cakey }}
  tls.crt: {{ .Values.tls.cacert }}
{{- end -}}
 # mongodb-init-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}-init
  namespace: {{ template "mongodb-replicaset.namespace" . }}
data:
  on-start.sh: |
{{ .Files.Get "init/on-start.sh" | indent 4 }}
{{- if .Values.initMongodStandalone }}
  initMongodStandalone.js: |
{{ .Values.initMongodStandalone | indent 4 }}
{{- end }}

 # mongodb-keyfile-secret.yaml
{{- if and (.Values.auth.enabled) (not .Values.auth.existingKeySecret) -}}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
{{- if .Values.secretAnnotations }}
  annotations:
{{ toYaml .Values.secretAnnotations | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.keySecret" . }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
type: Opaque
data:
  key.txt: {{ .Values.auth.key | b64enc }}
{{- end -}}
 # mongodb-metrics-secret.yaml
{{- if and (.Values.auth.enabled) (not .Values.auth.existingMetricsSecret) (.Values.metrics.enabled) -}}
apiVersion: v1
kind: Secret
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
{{- if .Values.secretAnnotations }}
  annotations:
{{ toYaml .Values.secretAnnotations | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.metricsSecret" . }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
type: Opaque
data:
  user: {{ .Values.auth.metricsUser | b64enc }}
  password: {{ .Values.auth.metricsPassword | b64enc }}
{{- end -}}
 # mongodb-mongodb-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}-mongodb
  namespace: {{ template "mongodb-replicaset.namespace" . }}
data:
  mongod.conf: |
{{ toYaml .Values.configmap | indent 4 }}
 # mongodb-poddisruptionbudget.yaml
{{- if .Values.podDisruptionBudget -}}
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
spec:
  selector:
    matchLabels:
      app: {{ template "mongodb-replicaset.name" . }}
      release: {{ .Release.Name }}
{{ toYaml .Values.podDisruptionBudget | indent 2 }}
{{- end -}}
 # mongodb-service-client.yaml
{{- if .Values.clientService.enabled -}}
# An optional headless service for client applications to use
apiVersion: v1
kind: Service
metadata:
  annotations:
  {{- if .Values.serviceAnnotations }}
{{ toYaml .Values.serviceAnnotations | indent 4 }}
  {{- end }}
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}-client
  namespace: {{ template "mongodb-replicaset.namespace" . }}
spec:
  type: ClusterIP
  clusterIP: None
  ports:
    - name: mongodb
      port: {{ .Values.port }}
{{- if .Values.metrics.enabled }}
    - name: metrics
      port: {{ .Values.metrics.port }}
      targetPort: metrics
{{- end }}
  selector:
    app: {{ template "mongodb-replicaset.name" . }}
    release: {{ .Release.Name }}
{{- end -}}
 # mongodb-service.yaml
# A headless service to create DNS records for discovery purposes. Use the -client service to connect applications
apiVersion: v1
kind: Service
metadata:
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
spec:
  type: ClusterIP
  clusterIP: None
  ports:
    - name: mongodb
      port: {{ .Values.port }}
  publishNotReadyAddresses: true
  selector:
    app: {{ template "mongodb-replicaset.name" . }}
    release: {{ .Release.Name }}
 # mongodb-serviceaccount.yaml
{{- if .Values.serviceAccount -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ .Values.serviceAccount }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  {{- if .Values.extraLabels }}
  {{ toYaml .Values.extraLabels | indent 4 }}
  {{- end }}
{{- end -}}
 # mongodb-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ template "mongodb-replicaset.chart" . }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 4 }}
{{- end }}
{{- if .Values.statefulSetAnnotations }}
  annotations:
{{ toYaml .Values.statefulSetAnnotations | indent 4 }}
{{- end }}
  name: {{ template "mongodb-replicaset.fullname" . }}
  namespace: {{ template "mongodb-replicaset.namespace" . }}
spec:
{{- if .Values.updateStrategy }}
  updateStrategy:
{{ toYaml .Values.updateStrategy | indent 4 }}
{{- end }}
  selector:
    matchLabels:
      app: {{ template "mongodb-replicaset.name" . }}
      release: {{ .Release.Name }}
  serviceName: {{ template "mongodb-replicaset.fullname" . }}
  replicas: {{ .Values.replicas }}
  template:
    metadata:
      labels:
        app: {{ template "mongodb-replicaset.name" . }}
        release: {{ .Release.Name }}
{{- if .Values.extraLabels }}
{{ toYaml .Values.extraLabels | indent 8 }}
{{- end }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/mongodb-mongodb-configmap.yaml") . | sha256sum }}
      {{- if and (.Values.metrics.prometheusServiceDiscovery) (.Values.metrics.enabled) }}
        prometheus.io/scrape: "true"
        prometheus.io/port: {{ .Values.metrics.port | quote }}
        prometheus.io/path: {{ .Values.metrics.path | quote }}
      {{- end }}
      {{- if .Values.podAnnotations }}
{{ toYaml .Values.podAnnotations | indent 8 }}
      {{- end }}
    spec:
    {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
    {{- end }}
    {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
      {{- range .Values.imagePullSecrets }}
        - name: {{ . }}
      {{- end}}
    {{- end }}
    {{- if .Values.securityContext.enabled }}
      securityContext:
        runAsUser: {{ .Values.securityContext.runAsUser }}
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsNonRoot: {{ .Values.securityContext.runAsNonRoot }}
    {{- end }}
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      {{- if .Values.serviceAccount }}
      serviceAccountName: {{ .Values.serviceAccount }}
      {{- end }}
      initContainers:
        - name: copy-config
          image: "{{ .Values.copyConfigImage.repository }}:{{ .Values.copyConfigImage.tag }}"
          imagePullPolicy: {{ .Values.copyConfigImage.pullPolicy | quote }}
          command:
            - "sh"
          args:
            - "-c"
            - |
              set -e
              set -x

              cp /configdb-readonly/mongod.conf /data/configdb/mongod.conf

            {{- if .Values.tls.enabled }}
              cp /ca-readonly/tls.key /data/configdb/tls.key
              cp /ca-readonly/tls.crt /data/configdb/tls.crt
            {{- end }}

            {{- if .Values.auth.enabled }}
              cp /keydir-readonly/key.txt /data/configdb/key.txt
              chmod 600 /data/configdb/key.txt
            {{- end }}
          volumeMounts:
            - name: workdir
              mountPath: /work-dir
            - name: config
              mountPath: /configdb-readonly
            - name: configdir
              mountPath: /data/configdb
          {{- if .Values.tls.enabled }}
            - name: ca
              mountPath: /ca-readonly
          {{- end }}
          {{- if .Values.auth.enabled }}
            - name: keydir
              mountPath: /keydir-readonly
          {{- end }}
          resources:
{{ toYaml .Values.init.resources | indent 12 }}
        - name: install
          image: "{{ .Values.installImage.repository }}:{{ .Values.installImage.tag }}"
          args:
            - --work-dir=/work-dir
          imagePullPolicy: "{{ .Values.installImage.pullPolicy }}"
          volumeMounts:
            - name: workdir
              mountPath: /work-dir
          resources:
{{ toYaml .Values.init.resources | indent 12 }}
        - name: bootstrap
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          command:
            - /work-dir/peer-finder
          args:
            - -on-start=/init/on-start.sh
            - "-service={{ template "mongodb-replicaset.fullname" . }}"
          imagePullPolicy: "{{ .Values.image.pullPolicy }}"
          env:
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
            - name: REPLICA_SET
              value: {{ .Values.replicaSetName }}
            - name: TIMEOUT
              value: "{{ .Values.init.timeout }}"
            - name: SKIP_INIT
              value: "{{ .Values.skipInitialization }}"
            - name: TLS_MODE
              value: {{ .Values.tls.mode }}
          {{- if .Values.auth.enabled }}
            - name: AUTH
              value: "true"
            - name: ADMIN_USER
              valueFrom:
                secretKeyRef:
                  name: "{{ template "mongodb-replicaset.adminSecret" . }}"
                  key: user
            - name: ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: "{{ template "mongodb-replicaset.adminSecret" . }}"
                  key: password
          {{- if .Values.metrics.enabled }}
            - name: METRICS
              value: "true"
            - name: METRICS_USER
              valueFrom:
                secretKeyRef:
                  name: "{{ template "mongodb-replicaset.metricsSecret" . }}"
                  key: user
            - name: METRICS_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: "{{ template "mongodb-replicaset.metricsSecret" . }}"
                  key: password
          {{- end }}
          {{- end }}
          volumeMounts:
            - name: workdir
              mountPath: /work-dir
            - name: init
              mountPath: /init
            - name: configdir
              mountPath: /data/configdb
            - name: datadir
              mountPath: /data/db
          resources:
{{ toYaml .Values.init.resources | indent 12 }}
      containers:
        - name: {{ template "mongodb-replicaset.name" . }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: "{{ .Values.image.pullPolicy }}"
        {{- if .Values.extraVars }}
          env:
{{ toYaml .Values.extraVars | indent 12 }}
        {{- end }}
          ports:
            - name: mongodb
              containerPort: 27017
          resources:
{{ toYaml .Values.resources | indent 12 }}
          command:
            - mongod
          args:
            - --config=/data/configdb/mongod.conf
            - --dbpath=/data/db
            - --replSet={{ .Values.replicaSetName }}
            - --port=27017
            - --bind_ip=0.0.0.0
          {{- if .Values.auth.enabled }}
            - --auth
            - --keyFile=/data/configdb/key.txt
          {{- end }}
          {{- if .Values.tls.enabled }}
            - --sslMode={{ .Values.tls.mode }}
            - --sslCAFile=/data/configdb/tls.crt
            - --sslPEMKeyFile=/work-dir/mongo.pem
          {{- end }}
          livenessProbe:
            exec:
              command:
                - mongo
              {{- if .Values.tls.enabled }}
                - --ssl
                - --sslCAFile=/data/configdb/tls.crt
                - --sslPEMKeyFile=/work-dir/mongo.pem
              {{- end }}
                - --eval
                - "db.adminCommand('ping')"
            initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
            periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
            successThreshold: {{ .Values.livenessProbe.successThreshold }}
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
          startupProbe:
            exec:
              command:
                - mongo
              {{- if .Values.tls.enabled }}
                - --ssl
                - --sslCAFile=/data/configdb/tls.crt
                - --sslPEMKeyFile=/work-dir/mongo.pem
              {{- end }}
                - --eval
                - "db.adminCommand('ping')"
            initialDelaySeconds: {{ .Values.startupProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.startupProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.startupProbe.failureThreshold }}
            periodSeconds: {{ .Values.startupProbe.periodSeconds }}
            successThreshold: {{ .Values.startupProbe.successThreshold }}
{{- end }}
          readinessProbe:
            exec:
              command:
                - mongo
              {{- if .Values.tls.enabled }}
                - --ssl
                - --sslCAFile=/data/configdb/tls.crt
                - --sslPEMKeyFile=/work-dir/mongo.pem
              {{- end }}
                - --eval
                - "db.adminCommand('ping')"
            initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
            periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
            successThreshold: {{ .Values.readinessProbe.successThreshold }}
          volumeMounts:
            - name: datadir
              mountPath: /data/db
            - name: configdir
              mountPath: /data/configdb
            - name: workdir
              mountPath: /work-dir
{{ if .Values.metrics.enabled }}
        - name: metrics
          image: "{{ .Values.metrics.image.repository }}:{{ .Values.metrics.image.tag }}"
          imagePullPolicy: {{ .Values.metrics.image.pullPolicy | quote }}
          command:
            - sh
            - -c
            - >-
              /bin/mongodb_exporter
              --mongodb.uri {{ template "mongodb-replicaset.connection-string" . }}
              --web.telemetry-path={{ .Values.metrics.path }}
              --web.listen-address=:{{ .Values.metrics.port }}
          volumeMounts:
          {{- if and (.Values.tls.enabled) }}
            - name: ca
              mountPath: /ca
              readOnly: true
          {{- end }}
            - name: workdir
              mountPath: /work-dir
              readOnly: true
          env:
          {{- if .Values.auth.enabled }}
            - name: METRICS_USER
              valueFrom:
                secretKeyRef:
                  name: "{{ template "mongodb-replicaset.metricsSecret" . }}"
                  key: user
            - name: METRICS_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: "{{ template "mongodb-replicaset.metricsSecret" . }}"
                  key: password
          {{- end }}
          ports:
            - name: metrics
              containerPort: {{ .Values.metrics.port  }}
          resources:
{{ toYaml .Values.metrics.resources | indent 12 }}
          {{- if .Values.metrics.securityContext.enabled }}
          securityContext:
            runAsUser: {{ .Values.metrics.securityContext.runAsUser }}
          {{- end }}
          livenessProbe:
            exec:
              command:
                - sh
                - -c
                - >-
                  /bin/mongodb_exporter
                  --mongodb.uri {{ template "mongodb-replicaset.connection-string" . }}
                  --test
            initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
{{- if semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion }}
          startupProbe:
            exec:
              command:
                - sh
                - -c
                - >-
                  /bin/mongodb_exporter
                  --mongodb.uri {{ template "mongodb-replicaset.connection-string" . }}
                  --test
            initialDelaySeconds: {{ .Values.startupProbe.initialDelaySeconds }}
            timeoutSeconds: {{ .Values.startupProbe.timeoutSeconds }}
            failureThreshold: {{ .Values.startupProbe.failureThreshold }}
            periodSeconds: {{ .Values.startupProbe.periodSeconds }}
            successThreshold: {{ .Values.startupProbe.successThreshold }}
{{- end }}
{{ end }}
        {{- if .Values.extraContainers }}
        {{- tpl (toYaml .Values.extraContainers) . | nindent 8 }}
        {{- end }}
   {{- with .Values.nodeSelector }}
      nodeSelector:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.affinity }}
      affinity:
{{ toYaml . | indent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
{{ toYaml . | indent 8 }}
    {{- end }}
      volumes:
        - name: config
          configMap:
            name: {{ template "mongodb-replicaset.fullname" . }}-mongodb
        - name: init
          configMap:
            defaultMode: 0755
            name: {{ template "mongodb-replicaset.fullname" . }}-init
        {{- if .Values.tls.enabled }}
        - name: ca
          secret:
            defaultMode: 0400
            secretName: {{ template "mongodb-replicaset.fullname" . }}-ca
        {{- end }}
        {{- if .Values.auth.enabled }}
        - name: keydir
          secret:
            defaultMode: 0400
            secretName: {{ template "mongodb-replicaset.keySecret" . }}
        {{- end }}
        - name: workdir
          emptyDir: {}
        - name: configdir
          emptyDir: {}
{{- if .Values.extraVolumes }}
{{- tpl (toYaml .Values.extraVolumes) . | nindent 8 }}
{{- end }}
{{- if .Values.persistentVolume.enabled }}
  volumeClaimTemplates:
    - metadata:
        name: datadir
        annotations:
        {{- range $key, $value := .Values.persistentVolume.annotations }}
          {{ $key }}: "{{ $value }}"
        {{- end }}
      spec:
        accessModes:
        {{- range .Values.persistentVolume.accessModes }}
          - {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistentVolume.size | quote }}
      {{- if .Values.persistentVolume.storageClass }}
      {{- if (eq "-" .Values.persistentVolume.storageClass) }}
        storageClassName: ""
      {{- else }}
        storageClassName: "{{ .Values.persistentVolume.storageClass }}"
      {{- end }}
      {{- end }}
{{- else }}
        - name: datadir
          emptyDir: {}
{{- end }}
 # mongodb-up-test-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "mongodb-replicaset.fullname" . }}-tests
  namespace: {{ template "mongodb-replicaset.namespace" . }}
data:
  mongodb-up-test.sh: |
{{ .Files.Get "tests/mongodb-up-test.sh" | indent 4 }}
 # mongodb-up-test-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  labels:
    app: {{ template "mongodb-replicaset.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version }}
    heritage: {{ .Release.Service }}
    release: {{ .Release.Name }}
  name: {{ template "mongodb-replicaset.fullname" . }}-test
  namespace: {{ template "mongodb-replicaset.namespace" . }}
  annotations:
    "helm.sh/hook": test-success
spec:
  initContainers:
    - name: test-framework
      image: dduportal/bats:0.4.0
      command:
        - bash
        - -c
        - |
          set -ex
          # copy bats to tools dir
          cp -R /usr/local/libexec/ /tools/bats/
      volumeMounts:
        - name: tools
          mountPath: /tools
  containers:
    - name: mongo
      image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
      command:
        - /tools/bats/bats
        - -t
        - /tests/mongodb-up-test.sh
      env:
        - name: FULL_NAME
          value: {{ template "mongodb-replicaset.fullname" . }}
        - name: NAMESPACE
          value: {{ .Release.Namespace }}
        - name: REPLICAS
          value: "{{ .Values.replicas }}"
      {{- if .Values.auth.enabled }}
        - name: AUTH
          value: "true"
        - name: ADMIN_USER
          valueFrom:
            secretKeyRef:
              name: "{{ template "mongodb-replicaset.adminSecret" . }}"
              key: user
        - name: ADMIN_PASSWORD
          valueFrom:
            secretKeyRef:
              name: "{{ template "mongodb-replicaset.adminSecret" . }}"
              key: password
      {{- end }}
      volumeMounts:
        - name: tools
          mountPath: /tools
        - name: tests
          mountPath: /tests
      {{- if .Values.tls.enabled }}
        - name: tls
          mountPath: /tls
      {{- end }}
  volumes:
    - name: tools
      emptyDir: {}
    - name: tests
      configMap:
        name: {{ template "mongodb-replicaset.fullname" . }}-tests
  {{- if .Values.tls.enabled }}
    - name: tls
      secret:
        secretName: {{ template "mongodb-replicaset.fullname" . }}-ca
        items:
          - key: tls.crt
            path: tls.crt
          - key: tls.key
            path: tls.key
  {{- end }}
  restartPolicy: Never

# Override the name of the chart, which in turn changes the name of the containers, services etc.
nameOverride: ""
fullnameOverride: ""

# Override the deployment namespace
global: {}
# global:
#   namespaceOverride: ""

replicas: 3
port: 27017

## Setting this will skip the replicaset and user creation process during bootstrapping
skipInitialization: false

replicaSetName: rs0

podDisruptionBudget: {}
  # maxUnavailable: 1
  # minAvailable: 2

# updateStrategy:
  # type: RollingUpdate

auth:
  enabled: false
  existingKeySecret: ""
  existingAdminSecret: ""
  existingMetricsSecret: ""
  # adminUser: username
  # adminPassword: password
  # metricsUser: metrics
  # metricsPassword: password
  # key: keycontent

## Optionally specify an array of imagePullSecrets.
## Secrets must be manually created in the namespace.
## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
##
imagePullSecrets: []
#   - myRegistrKeySecretName

# Specs for the Docker image for the init container that establishes the replica set
installImage:
  repository: unguiculus/mongodb-install
  tag: 0.7
  pullPolicy: IfNotPresent

# Specs for the Docker image for the copyConfig init container
copyConfigImage:
  repository: busybox
  tag: 1.29.3
  pullPolicy: IfNotPresent

# Specs for the MongoDB image
image:
  repository: mongo
  tag: 3.6
  pullPolicy: IfNotPresent

# Additional environment variables to be set in the container
extraVars: {}
# - name: TCMALLOC_AGGRESSIVE_DECOMMIT
#   value: "true"

# Prometheus Metrics Exporter
metrics:
  enabled: false
  image:
    repository: bitnami/mongodb-exporter
    tag: 0.11.0
    pullPolicy: IfNotPresent
  port: 9216
  path: "/metrics"
  prometheusServiceDiscovery: true
  resources: {}
  securityContext:
    enabled: true
    runAsUser: 1001

serviceAccount: ""

# Annotations to be added to MongoDB pods
podAnnotations: {}

securityContext:
  enabled: true
  runAsUser: 999
  fsGroup: 999
  runAsNonRoot: true

init:
  resources: {}
  timeout: 900

resources: {}
# limits:
#   cpu: 500m
#   memory: 512Mi
# requests:
#   cpu: 100m
#   memory: 256Mi

## Node selector
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector
nodeSelector: {}

affinity: {}

tolerations: []

# Additional containers to add to the StatefulSet
extraContainers: []
#  - name: mongo-sidecar
#    image: stefanprodan/mgob:latest
#    ports:
#    - name: sidecar-http
#      containerPort: 8090
#    volumeMounts:
#    - mountPath: /config/test1.yml
#      name: mgob-config
#      subPath: test1.yml
#    - name: mgob-storage
#      mountPath: /storage

extraLabels: {}

## Additional volumes which can be used by sidecar containers
extraVolumes: []
# - name: mgob-config
#   configMap:
#     name: mgob-config

priorityClassName: ""

persistentVolume:
  enabled: true
  ## mongodb-replicaset data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  storageClass: ""
  accessModes:
    - ReadWriteOnce
  size: 10Gi
  annotations: {}

# Annotations to be added to the secrets
secretAnnotations: {}

# Annotations to be added to the service
serviceAnnotations: {}

# Annotations to be added to the statefulSet
statefulSetAnnotations: {}

terminationGracePeriodSeconds: 30

tls:
  # Enable or disable MongoDB TLS support
  enabled: false
  # Set the SSL operation mode (disabled|allowSSL|preferSSL|requireSSL)
  mode: requireSSL
  # Please generate your own TLS CA by generating it via:
  # $ openssl genrsa -out ca.key 2048
  # $ openssl req -x509 -new -nodes -key ca.key -days 10000 -out ca.crt -subj "/CN=mydomain.com"
  # After that you can base64 encode it and paste it here:
  # $ cat ca.key | base64 -w0
  # cacert:
  # cakey:

# Entries for the MongoDB config file
configmap: {}

# Javascript code to execute on each replica at initContainer time
# This is the recommended way to create indexes on replicasets.
# Below is an example that creates indexes in foreground on each replica in standalone mode.
# ref: https://docs.mongodb.com/manual/tutorial/build-indexes-on-replica-sets/
# initMongodStandalone: |+
#   db = db.getSiblingDB("mydb")
#   db.my_users.createIndex({email: 1})
initMongodStandalone: ""

# Readiness probe
readinessProbe:
  initialDelaySeconds: 5
  timeoutSeconds: 1
  failureThreshold: 3
  periodSeconds: 10
  successThreshold: 1

# Liveness probe
livenessProbe:
  initialDelaySeconds: 30
  timeoutSeconds: 5
  failureThreshold: 3
  periodSeconds: 10
  successThreshold: 1

# Startup probe, will only be added since Kubernetes v1.16 or higher
# When you have a lot of collections/indices, MongoDB need some time to start
startupProbe:
  initialDelaySeconds: 5
  timeoutSeconds: 5
  failureThreshold: 60
  periodSeconds: 10
  successThreshold: 2

# Enables/disables the headless client service
clientService:
  enabled: true
