{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

apiVersion: {{ ternary (include "common.capabilities.deployment.apiVersion" .) (include "common.capabilities.statefulset.apiVersion" .) (eq (lower .Values.grafana.kind) "deployment") }}
kind: {{ ternary "Deployment" "StatefulSet" (eq (lower .Values.grafana.kind) "deployment") }}
metadata:
  name: {{ include "common.names.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: grafana
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  replicas: {{ .Values.grafana.replicaCount }}
  {{- if eq (lower .Values.grafana.kind) "statefulset" }}
  serviceName: {{ printf "%s-headless" (include "common.names.fullname" .) | trunc 63 | trimSuffix "-" }}
  {{- if .Values.grafana.podManagementPolicy }}
  podManagementPolicy: {{ .Values.grafana.podManagementPolicy }}
  {{- end }}
  {{- end }}
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.grafana.podLabels .Values.commonLabels ) "context" . ) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/component: grafana
  {{- if .Values.grafana.updateStrategy }}
  {{ ternary "strategy" "updateStrategy" (eq (lower .Values.grafana.kind) "deployment") }}: {{ include "common.tplvalues.render" (dict "value" .Values.grafana.updateStrategy "context" .) | nindent 4 }}
  {{- end }}
  template:
    metadata:
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/component: grafana
      annotations:
        {{- if (include "grafana.createAdminSecret" .) }}
        checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
        {{- end }}
        {{- if (include "grafana.createSMTPSecret" .) }}
        checksum/smtp-secret: {{ include (print $.Template.BasePath "/smtp-secret.yaml") . | sha256sum }}
        {{- end }}
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        checksum/dashboard-provider: {{ include (print $.Template.BasePath "/dashboard-provider.yaml") . | sha256sum }}
        {{- if and .Values.ldap.enabled (or (not (empty .Values.ldap.configuration)) (not (empty .Values.ldap.uri))) (empty .Values.ldap.configMapName) (empty .Values.ldap.secretName) }}
        checksum/ldap: {{ include (print $.Template.BasePath "/ldap-secret.yaml") . | sha256sum }}
        {{- end }}
        {{- if .Values.grafana.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.grafana.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
    spec:
      {{- include "grafana.imagePullSecrets" . | nindent 6 }}
      automountServiceAccountToken: {{ .Values.grafana.automountServiceAccountToken }}
      {{- if .Values.grafana.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "grafana.serviceAccountName" . }}
      {{- if .Values.grafana.schedulerName }}
      schedulerName: {{ .Values.grafana.schedulerName | quote }}
      {{- end }}
      {{- if .Values.grafana.priorityClassName }}
      priorityClassName: {{ .Values.grafana.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.grafana.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.grafana.podAffinityPreset "component" "grafana" "customLabels" $podLabels "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.grafana.podAntiAffinityPreset "component" "grafana" "customLabels" $podLabels "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.grafana.nodeAffinityPreset.type "key" .Values.grafana.nodeAffinityPreset.key "values" .Values.grafana.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.grafana.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.grafana.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.tolerations "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.grafana.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.topologySpreadConstraints "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.grafana.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.grafana.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.grafana.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.grafana.terminationGracePeriodSeconds }}
      {{- end }}
      enableServiceLinks: {{ .Values.grafana.enableServiceLinks }}
      initContainers:
        {{- if .Values.volumePermissions.enabled }}
        - name: volume-permissions
          image: {{ include "volumePermissions.image" . }}
          imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }}
          command:
            - /bin/bash
          args:
            - -ec
            - |
              mkdir -p /bitnami/grafana
              find /bitnami/grafana -mindepth 1 -maxdepth 1 -not -name ".snapshot" -not -name "lost+found" | xargs -r chown -R {{ .Values.grafana.containerSecurityContext.runAsUser }}:{{ .Values.grafana.podSecurityContext.fsGroup }}
          securityContext: {{- include "common.tplvalues.render" (dict "value" .Values.volumePermissions.containerSecurityContext "context" $) | nindent 12 }}
          {{- if .Values.volumePermissions.resources }}
          resources: {{- include "common.tplvalues.render" (dict "value" .Values.volumePermissions.resources "context" $) | nindent 12 }}
          {{- else if ne .Values.volumePermissions.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.volumePermissions.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: data
              mountPath: /bitnami/grafana
        {{- end }}
        {{- if .Values.grafana.initContainers }}
          {{- include "common.tplvalues.render" (dict "value" .Values.grafana.initContainers "context" $) | nindent 8 }}
        {{- end }}
      containers:
        - name: grafana
          image: {{ include "grafana.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.grafana.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.grafana.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.grafana.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.command "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.args "context" $) | nindent 12 }}
          {{- else if .Values.grafana.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.args "context" $) | nindent 12 }}
          {{- end }}
          envFrom:
            - configMapRef:
                name: {{ include "common.names.fullname" . }}-envvars
            {{- if .Values.grafana.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.grafana.extraEnvVarsCM "context" $) }}
                optional: {{ include "common.tplvalues.render" (dict "value" .Values.grafana.extraEnvVarsCMOptional "context" $) }}
            {{- end }}
            {{- if .Values.grafana.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.grafana.extraEnvVarsSecret "context" $) }}
                optional: {{ include "common.tplvalues.render" (dict "value" .Values.grafana.extraEnvVarsSecretOptional "context" $) }}
            {{- end }}
          env:
            {{- if .Values.usePasswordFiles }}
            - name: GF_SECURITY_ADMIN_PASSWORD_FILE
              value: {{ printf "/opt/bitnami/grafana/secrets/%s" (include "grafana.adminSecretPasswordKey" .) }}
            {{- else }}
            - name: GF_SECURITY_ADMIN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "grafana.adminSecretName" . }}
                  key: {{ include "grafana.adminSecretPasswordKey" . }}
            {{- end }}
            {{- if .Values.smtp.enabled }}
            - name: GF_SMTP_ENABLED
              value: "true"
            {{- if .Values.smtp.host }}
            - name: GF_SMTP_HOST
              value: {{ .Values.smtp.host }}
            {{- end }}
            {{- if .Values.smtp.fromAddress }}
            - name: GF_SMTP_FROM_ADDRESS
              value: {{ .Values.smtp.fromAddress }}
            {{- end }}
            {{- if .Values.smtp.fromName }}
            - name: GF_SMTP_FROM_NAME
              value: {{ .Values.smtp.fromName }}
            {{- end }}
            {{- if .Values.smtp.skipVerify }}
            - name: GF_SMTP_SKIP_VERIFY
              value: "{{ .Values.smtp.skipVerify }}"
            {{- end }}
            {{- if .Values.usePasswordFiles }}
            - name: GF_SMTP_USER_FILE
              value: {{ printf "/opt/bitnami/grafana/secrets/%s" (include "grafana.smtpSecretUserKey" .) }}
            - name: GF_SMTP_PASSWORD_FILE
              value: {{ printf "/opt/bitnami/grafana/secrets/%s" (include "grafana.smtpSecretPasswordKey" .) }}
            {{- else }}
            - name: GF_SMTP_USER
              valueFrom:
                secretKeyRef:
                  name: {{ include "grafana.smtpSecretName" . }}
                  key: {{ include "grafana.smtpSecretUserKey" . }}
            - name: GF_SMTP_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "grafana.smtpSecretName" . }}
                  key: {{ include "grafana.smtpSecretPasswordKey" . }}
            {{- end }}
            {{- end }}
            {{- if .Values.grafana.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.grafana.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          volumeMounts:
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/grafana/conf
              subPath: app-conf-dir
            - name: empty-dir
              mountPath: /opt/bitnami/grafana/tmp
              subPath: app-tmp-dir
            - name: empty-dir
              mountPath: /bitnami/grafana
              subPath: app-volume-dir
            {{- if and .Values.usePasswordFiles }}
            - name: grafana-secrets
              mountPath: /opt/bitnami/grafana/secrets
            {{- end }}
            {{- if .Values.config.useGrafanaIniFile }}
            - name: grafana-ini
              mountPath: /opt/bitnami/grafana/conf/grafana.ini
              subPath: grafana.ini
            {{- end }}
            - name: data
              mountPath: /opt/bitnami/grafana/data
            {{- if .Values.dashboardsProvider.enabled }}
            - name: dashboards-provider
              mountPath: /opt/bitnami/grafana/conf.default/provisioning/dashboards
            {{- end }}
            {{- range .Values.dashboardsConfigMaps }}
            - name: {{ include "common.tplvalues.render" ( dict "value" .configMapName "context" $ ) }}
            {{- if .folderName }}
              mountPath: /opt/bitnami/grafana/dashboards/{{ include "common.tplvalues.render" ( dict "value" .folderName "context" $ ) }}/{{ include "common.tplvalues.render" ( dict "value" .fileName "context" $ ) }}
            {{- else }}
              mountPath: /opt/bitnami/grafana/dashboards/{{ include "common.tplvalues.render" ( dict "value" .fileName "context" $ ) }}
            {{- end }}
              subPath: {{ include "common.tplvalues.render" ( dict "value" .fileName "context" $ ) }}
            {{- end }}
            {{- if or (.Values.datasources.secretName) (.Values.datasources.secretDefinition) }}
            - name: datasources
              mountPath: /opt/bitnami/grafana/conf.default/provisioning/datasources
            {{- end }}
            {{- if .Values.notifiers.configMapName }}
            - name: notifiers
              mountPath: /opt/bitnami/grafana/conf.default/provisioning/notifiers
            {{- end }}
            {{- if .Values.alerting.configMapName }}
            - name: alerting
              mountPath: /opt/bitnami/grafana/conf.default/provisioning/alerting
            {{- end }}
            {{- if .Values.ldap.enabled }}
            - name: ldap
              mountPath: /opt/bitnami/grafana/conf.default/ldap.toml
              subPath: ldap.toml
            {{- end }}
            {{- if and .Values.ldap.tls.enabled .Values.ldap.tls.certificatesSecret }}
            - name: ldap-tls
              mountPath: {{ include "common.tplvalues.render" (dict "value" .Values.ldap.tls.certificatesMountPath "context" $) }}
            {{- end }}
            {{- range .Values.grafana.extraConfigmaps }}
            - name: {{ include "common.tplvalues.render" (dict "value" .name "context" $) }}
              mountPath: {{ include "common.tplvalues.render" (dict "value" .mountPath "context" $) }}
              subPath: {{ include "common.tplvalues.render" (dict "value" .subPath "context" $) | default "" }}
              readOnly: {{ include "common.tplvalues.render" (dict "value" .readOnly "context" $) }}
            {{- end }}
            {{- if .Values.grafana.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.grafana.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
          ports:
            - name: dashboard
              containerPort: {{ .Values.grafana.containerPorts.grafana }}
              protocol: TCP
            {{- if .Values.grafana.extraPorts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.grafana.extraPorts "context" $) | nindent 12 }}
            {{- end }}
          {{- if .Values.grafana.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.grafana.livenessProbe.enabled }}
          livenessProbe:
            tcpSocket:
              port: dashboard
            initialDelaySeconds: {{ .Values.grafana.livenessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.grafana.livenessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.grafana.livenessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.grafana.livenessProbe.successThreshold }}
            failureThreshold: {{ .Values.grafana.livenessProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.grafana.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.grafana.readinessProbe.enabled }}
          readinessProbe:
            httpGet:
              path: {{ .Values.grafana.readinessProbe.path }}
              port: dashboard
              scheme: {{ .Values.grafana.readinessProbe.scheme }}
            initialDelaySeconds: {{ .Values.grafana.readinessProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.grafana.readinessProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.grafana.readinessProbe.timeoutSeconds }}
            successThreshold: {{ .Values.grafana.readinessProbe.successThreshold }}
            failureThreshold: {{ .Values.grafana.readinessProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.grafana.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.grafana.startupProbe.enabled }}
          startupProbe:
            httpGet:
              path: {{ .Values.grafana.startupProbe.path }}
              port: dashboard
              scheme: {{ .Values.grafana.startupProbe.scheme }}
            initialDelaySeconds: {{ .Values.grafana.startupProbe.initialDelaySeconds }}
            periodSeconds: {{ .Values.grafana.startupProbe.periodSeconds }}
            timeoutSeconds: {{ .Values.grafana.startupProbe.timeoutSeconds }}
            successThreshold: {{ .Values.grafana.startupProbe.successThreshold }}
            failureThreshold: {{ .Values.grafana.startupProbe.failureThreshold }}
          {{- end }}
          {{- if .Values.grafana.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.grafana.resources }}
          resources: {{- include "common.tplvalues.render" (dict "value" .Values.grafana.resources "context" $) | nindent 12 }}
          {{- else if ne .Values.grafana.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.grafana.resourcesPreset) | nindent 12 }}
          {{- end }}
        {{- if .Values.grafana.sidecars }}
        {{- include "common.tplvalues.render" (dict "value" .Values.grafana.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        {{- if and .Values.usePasswordFiles }}
        - name: grafana-secrets
          projected:
            sources:
              - secret:
                  name:  {{ include "grafana.adminSecretName" . }}
              {{- if .Values.smtp.enabled }}
              - secret:
                  name:  {{ include "grafana.smtpSecretName" . }}
              {{- end }}
        {{- end }}
        {{- if eq (lower .Values.grafana.kind) "deployment" }}
        - name: data
        {{- if .Values.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ include "common.tplvalues.render" ( dict "value" .Values.persistence.existingClaim "context" $) | default (include "common.names.fullname" .) }}
        {{- else }}
          emptyDir: {}
        {{- end }}
        {{- end }}
        {{- if .Values.ldap.enabled }}
        - name: ldap
          {{- if not (empty .Values.ldap.configMapName) }}
          configMap:
            name: {{ include "common.tplvalues.render" ( dict "value" .Values.ldap.configMapName "context" $) }}
          {{- else if not (empty .Values.ldap.secretName) }}
          secret:
            secretName: {{ include "common.tplvalues.render" ( dict "value" .Values.ldap.secretName "context" $) }}
          {{- else }}
          secret:
            secretName: {{ printf "%s-ldap-conf" (include "common.names.fullname" .) }}
          {{- end }}
        {{- end }}
        {{- if .Values.dashboardsProvider.enabled }}
        - name: dashboards-provider
          configMap:
            {{- if .Values.dashboardsProvider.configMapName }}
            name: {{ include "common.tplvalues.render" ( dict "value" .Values.dashboardsProvider.configMapName "context" $) }}
            {{- else }}
            name: {{ include "common.names.fullname" . }}-provider
            {{- end }}
        {{- end }}
{{- $dashboardConfigMapNames := list }}
{{- range .Values.dashboardsConfigMaps }}
  {{- $dashboardConfigMapNames = append $dashboardConfigMapNames .configMapName }}
{{- end }}
        {{- range $dashboardConfigMapNames | uniq }}
        - name: {{ include "common.tplvalues.render" ( dict "value" . "context" $ ) }}
          configMap:
            name: {{ include "common.tplvalues.render" ( dict "value" . "context" $ ) }}
        {{- end }}
        {{- if .Values.datasources.secretName }}
        - name: datasources
          secret:
            secretName: {{ include "common.tplvalues.render" ( dict "value" .Values.datasources.secretName "context" $) }}
        {{- else if .Values.datasources.secretDefinition }}
        - name: datasources
          secret:
            secretName: {{ include "common.names.fullname" . }}-datasources
        {{- end }}
        {{- if .Values.notifiers.configMapName }}
        - name: notifiers
          configMap:
            name: {{ include "common.tplvalues.render" (dict "value" .Values.notifiers.configMapName "context" $) }}
        {{- end }}
        {{- if .Values.alerting.configMapName }}
        - name: alerting
          configMap:
            name: {{ include "common.tplvalues.render" (dict "value" .Values.alerting.configMapName "context" $) }}
        {{- end }}
        {{- if .Values.config.useGrafanaIniFile }}
        - name: grafana-ini
          {{- if .Values.config.grafanaIniConfigMap }}
          configMap:
            name: {{ include "common.tplvalues.render" (dict "value" .Values.config.grafanaIniConfigMap "context" $) }}
          {{- else if .Values.config.grafanaIniSecret }}
          secret:
            secretName: {{ include "common.tplvalues.render" (dict "value" .Values.config.grafanaIniSecret "context" $) }}
          {{- end }}
        {{- end }}
        {{- if and .Values.ldap.tls.enabled .Values.ldap.tls.certificatesSecret }}
        - name: ldap-tls
          secret:
            secretName: {{ include "common.tplvalues.render" (dict "value" .Values.ldap.tls.certificatesSecret "context" $) }}
        {{- end }}
        {{- range .Values.grafana.extraConfigmaps }}
        - name: {{ include "common.tplvalues.render" (dict "value" .name "context" $) }}
          configMap:
            name: {{ include "common.tplvalues.render" (dict "value" .name "context" $) }}
        {{- end }}
        {{- if .Values.grafana.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.grafana.extraVolumes  "context" $) | nindent 8 }}
        {{- end }}
  {{- if and (eq (lower .Values.grafana.kind) "statefulset") .Values.persistence.enabled }}
  volumeClaimTemplates:
    - metadata:
        name: data
        {{- if .Values.persistence.annotations }}
        annotations: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.annotations "context" $) | nindent 10 }}
        {{- end }}
        {{- if .Values.persistence.labels }}
        labels: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.labels "context" $) | nindent 10 }}
        {{- end }}
      spec:
        accessModes:
        {{- if .Values.persistence.accessModes }}
          {{- range .Values.persistence.accessModes }}
          - {{ . | quote }}
          {{- end }}
        {{- else }}
          - {{ .Values.persistence.accessMode | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.persistence.size | quote }}
        {{- include "common.storage.class" (dict "persistence" .Values.persistence "global" .Values.global) | nindent 8 }}
        {{- if .Values.persistence.selector }}
        selector: {{- include "common.tplvalues.render" (dict "value" .Values.persistence.selector "context" $) | nindent 10 }}
        {{- end }}
  {{- end }}
