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

apiVersion: {{ include "common.capabilities.deployment.apiVersion" . }}
kind: Deployment
metadata:
  name: {{ template "cloudnative-pg.operator.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: cloudnative-pg
    app.kubernetes.io/component: operator
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  {{- if not .Values.operator.autoscaling.hpa.enabled }}
  replicas: {{ .Values.operator.replicaCount }}
  {{- end }}
  {{- if .Values.operator.updateStrategy }}
  strategy: {{- toYaml .Values.operator.updateStrategy | nindent 4 }}
  {{- end }}
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.operator.podLabels .Values.commonLabels) "context" . ) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/part-of: cloudnative-pg
      app.kubernetes.io/component: operator
  template:
    metadata:
      {{- if or .Values.operator.podAnnotations (include "cloudnative-pg.operator.useConfigMap" .) (include "cloudnative-pg.operator.useSecret" .) }}
      annotations:
        {{- if .Values.operator.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.operator.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
        {{- if (include "cloudnative-pg.operator.useConfigMap" .) }}
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        {{- end }}
        {{- if (include "cloudnative-pg.operator.useSecret" .)}}
        checksum/secret: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
        {{- end }}
      {{- end }}
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/part-of: cloudnative-pg
        app.kubernetes.io/component: operator
    spec:
      serviceAccountName: {{ template "cloudnative-pg.operator.serviceAccountName" . }}
      {{- include "cloudnative-pg.imagePullSecrets" . | nindent 6 }}
      automountServiceAccountToken: {{ .Values.operator.automountServiceAccountToken }}
      {{- if .Values.operator.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.operator.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.operator.affinity }}
      affinity: {{- include "common.tplvalues.render" ( dict "value" .Values.operator.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.operator.podAffinityPreset "component" "operator" "customLabels" $podLabels "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.operator.podAntiAffinityPreset "component" "operator" "customLabels" $podLabels "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.operator.nodeAffinityPreset.type "key" .Values.operator.nodeAffinityPreset.key "values" .Values.operator.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.operator.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" ( dict "value" .Values.operator.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.operator.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.operator.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.operator.priorityClassName }}
      priorityClassName: {{ .Values.operator.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.operator.schedulerName }}
      schedulerName: {{ .Values.operator.schedulerName | quote }}
      {{- end }}
      {{- if .Values.operator.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.operator.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.operator.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.operator.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.operator.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.operator.terminationGracePeriodSeconds }}
      {{- end }}
      {{- if .Values.operator.initContainers }}
      initContainers:
        {{- include "common.tplvalues.render" (dict "value" .Values.operator.initContainers "context" $) | nindent 8 }}
      {{- end }}
      containers:
        - name: cloudnative-pg
          image: {{ template "cloudnative-pg.operator.image" . }}
          imagePullPolicy: {{ .Values.operator.image.pullPolicy }}
          {{- if .Values.operator.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.operator.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.operator.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.operator.command "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.operator.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.operator.args "context" $) | nindent 12 }}
          {{- else }}
          args:
            - controller
            - --leader-elect
            - --max-concurrent-reconciles={{ .Values.operator.maxConcurrentReconciles }}
            {{- if (include "cloudnative-pg.operator.useConfigMap" .) }}
            - --config-map-name={{ include "cloudnative-pg.operator.configmapName" .}}
            {{- end }}
            {{- if (include "cloudnative-pg.operator.useSecret" .) }}
            - --secret-name={{ include "cloudnative-pg.operator.secretName" .}}
            {{- end }}
            - --webhook-port={{ .Values.operator.containerPorts.webhook }}
            - --metrics-bind-address=:{{ .Values.operator.containerPorts.metrics }}
            {{- if .Values.operator.image.debug }}
            - --log-level=trace
            {{- end }}
            {{- if .Values.operator.extraArgs }}
            {{- include "common.tplvalues.render" (dict "value" .Values.operator.extraArgs "context" $) | nindent 12 }}
            {{- end }}
          {{- end }}
          env:
            - name: OPERATOR_IMAGE_NAME
              value: {{ include "cloudnative-pg.operator.image" . | quote }}
            - name: POSTGRES_IMAGE_NAME
              value: {{ include "cloudnative-pg.postgresql.image" . }}
            {{- if (include "cloudnative-pg.operator.imagePullSecret" .) }}
            - name: PULL_SECRET_NAME
              value: {{ include "cloudnative-pg.operator.imagePullSecret" . | quote }}
            {{- end }}
            {{- if .Values.operator.metrics.enabled }}
            - name: {{ ternary "MONITORING_QUERIES_SECRET" "MONITORING_QUERIES_CONFIGMAP" .Values.operator.metrics.monitoringQueries.useSecret }}
              value: {{ include "cloudnative-pg.operator.monitoringQueriesName" . | quote }}
            {{- end }}
            {{- if not .Values.operator.watchAllNamespaces }}
            {{- $watchNamespaces := default (list (include "common.names.namespace" .)) .Values.operator.watchNamespaces }}
            - name: WATCH_NAMESPACE
              value: {{ join "," $watchNamespaces | quote }}
            {{- end }}
            - name: OPERATOR_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            {{- if .Values.operator.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.operator.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            {{- if .Values.operator.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.operator.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.operator.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.operator.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- if .Values.operator.resources }}
          resources: {{- toYaml .Values.operator.resources | nindent 12 }}
          {{- else if ne .Values.operator.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.operator.resourcesPreset) | nindent 12 }}
          {{- end }}
          ports:
            - name: http-metrics
              containerPort: {{ .Values.operator.containerPorts.metrics }}
            - name: http-webhook
              containerPort: {{ .Values.operator.containerPorts.webhook }}
          {{- if .Values.operator.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.operator.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.operator.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.operator.livenessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              {{- /* Not using http-webhook because it adds noise in the logs */}}
              port: http-metrics
          {{- end }}
          {{- if .Values.operator.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.operator.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.operator.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.operator.readinessProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /readyz
              port: http-webhook
              scheme: HTTPS
          {{- end }}
          {{- if .Values.operator.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.operator.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.operator.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.operator.startupProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /readyz
              port: http-webhook
              scheme: HTTPS
          {{- end }}
          {{- if .Values.operator.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.operator.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          volumeMounts:
              # Paths hardcoded in source code
              # https://github.com/cloudnative-pg/cloudnative-pg/blob/main/internal/cmd/manager/controller/controller.go#L51
            - name: empty-dir
              mountPath: /controller
              subPath: tmp-dir
            - name: empty-dir
              mountPath: /plugins
              subPath: plugins-dir
            - mountPath: /run/secrets/cnpg.io/webhook
              name: webhook-certificates
              {{- if .Values.operator.extraVolumeMounts }}
              {{- include "common.tplvalues.render" (dict "value" .Values.operator.extraVolumeMounts "context" $) | nindent 12 }}
              {{- end }}
        {{- if .Values.operator.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.operator.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        # Hardcoded in source code
        # https://github.com/cloudnative-pg/cloudnative-pg/blob/main/internal/cmd/manager/controller/controller.go#L51
        - name: webhook-certificates
          secret:
            defaultMode: 420
            optional: true
            secretName: cnpg-webhook-cert
        {{- if .Values.operator.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.operator.extraVolumes "context" $) | nindent 8 }}
        {{- end }}