{{- if .Values.clusterAgent.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ template "datadog.fullname" . }}-cluster-agent
  labels:
    helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}"
    app.kubernetes.io/name: "{{ template "datadog.fullname" . }}"
    app.kubernetes.io/instance: {{ .Release.Name | quote }}
    app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
    app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
spec:
  replicas: {{ .Values.clusterAgent.replicas }}
  strategy:
{{- if .Values.clusterAgent.strategy }}
{{ toYaml .Values.clusterAgent.strategy | indent 4 }}
{{- else }}
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
{{- end }}
  selector:
    matchLabels:
      app: {{ template "datadog.fullname" . }}-cluster-agent
        {{- if .Values.clusterAgent.podLabels }}
{{ toYaml .Values.clusterAgent.podLabels | indent 6 }}
        {{- end }}
  template:
    metadata:
      labels:
        app: {{ template "datadog.fullname" . }}-cluster-agent
        {{- if .Values.clusterAgent.podLabels }}
{{ toYaml .Values.clusterAgent.podLabels | indent 8 }}
        {{- end }}
      name: {{ template "datadog.fullname" . }}-cluster-agent
      annotations:
        {{- if .Values.clusterAgent.datadog_cluster_yaml }}
        checksum/clusteragent-config: {{ tpl (toYaml .Values.clusterAgent.datadog_cluster_yaml) . | sha256sum }}
        {{- end }}
        {{- if .Values.clusterAgent.confd }}
        checksum/confd-config: {{ tpl (toYaml .Values.clusterAgent.confd) . | sha256sum }}
        {{- end }}
        ad.datadoghq.com/cluster-agent.check_names: '["prometheus"]'
        ad.datadoghq.com/cluster-agent.init_configs: '[{}]'
        ad.datadoghq.com/cluster-agent.instances: |
          [{
            "prometheus_url": "http://%%host%%:5000/metrics",
            "namespace": "datadog.cluster_agent",
            "metrics": [
              "go_goroutines", "go_memstats_*", "process_*",
              "api_requests",
              "datadog_requests", "external_metrics", "rate_limit_queries_*",
              "cluster_checks_*"
            ]
          }]
      {{- if .Values.clusterAgent.podAnnotations }}
{{ toYaml .Values.clusterAgent.podAnnotations | indent 8 }}
      {{- end }}

    spec:
      {{- if .Values.clusterAgent.priorityClassName }}
      priorityClassName: "{{ .Values.clusterAgent.priorityClassName }}"
      {{- end }}
      {{- if .Values.clusterAgent.image.pullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.clusterAgent.image.pullSecrets | indent 8 }}
      {{- end }}
      serviceAccountName: {{ if .Values.clusterAgent.rbac.create }}{{ template "datadog.fullname" . }}-cluster-agent{{ else }}"{{ .Values.clusterAgent.rbac.serviceAccountName }}"{{ end }}
      {{- if .Values.clusterAgent.useHostNetwork }}
      hostNetwork: {{ .Values.clusterAgent.useHostNetwork }}
      dnsPolicy: ClusterFirstWithHostNet
      {{- end }}
      {{- if .Values.clusterAgent.dnsConfig }}
      dnsConfig:
{{ toYaml .Values.clusterAgent.dnsConfig | indent 8 }}
      {{- end }}
      containers:
      - name: cluster-agent
        image: "{{ .Values.clusterAgent.image.repository }}:{{ .Values.clusterAgent.image.tag }}"
        {{- with .Values.clusterAgent.command }}
        command: {{ range . }}
          - {{ . | quote }}
        {{- end }}
        {{- end }}
        imagePullPolicy: {{ .Values.clusterAgent.image.pullPolicy }}
        resources:
{{ toYaml .Values.clusterAgent.resources | indent 10 }}
        ports:
        - containerPort: 5005
          name: agentport
          protocol: TCP
        {{- if .Values.clusterAgent.metricsProvider.enabled }}
        - containerPort: {{ template "clusterAgent.metricsProvider.port" . }}
          name: metricsapi
          protocol: TCP
        {{- end }}
        env:
          - name: DD_HEALTH_PORT
            value: {{ .Values.clusterAgent.healthPort | quote }}
          - name: DD_API_KEY
            valueFrom:
              secretKeyRef:
                name: {{ template "datadog.apiSecretName" . }}
                key: api-key
                optional: true
          {{- if .Values.clusterAgent.metricsProvider.enabled }}
          - name: DD_APP_KEY
            valueFrom:
              secretKeyRef:
                name: {{ template "datadog.appKeySecretName" . }}
                key: app-key
          - name: DD_EXTERNAL_METRICS_PROVIDER_ENABLED
            value: {{ .Values.clusterAgent.metricsProvider.enabled | quote }}
          - name: DD_EXTERNAL_METRICS_PROVIDER_PORT
            value: {{ include "clusterAgent.metricsProvider.port" . | quote }}
          - name: DD_EXTERNAL_METRICS_PROVIDER_WPA_CONTROLLER
            value: {{ .Values.clusterAgent.metricsProvider.wpaController | quote }}
          - name: DD_EXTERNAL_METRICS_PROVIDER_USE_DATADOGMETRIC_CRD
            value: {{ .Values.clusterAgent.metricsProvider.useDatadogMetrics | quote }}
          {{- end }}
          {{- if .Values.clusterAgent.admissionController.enabled }}
          - name: DD_ADMISSION_CONTROLLER_ENABLED
            value: {{ .Values.clusterAgent.admissionController.enabled | quote }}
          - name: DD_ADMISSION_CONTROLLER_MUTATE_UNLABELLED
            value: {{ .Values.clusterAgent.admissionController.mutateUnlabelled | quote }}
          - name: DD_ADMISSION_CONTROLLER_SERVICE_NAME
            value: {{ template "datadog.fullname" . }}-cluster-agent-admission-controller
          {{- end }}
          {{- if .Values.datadog.clusterChecks.enabled }}
          - name: DD_CLUSTER_CHECKS_ENABLED
            value: {{ .Values.datadog.clusterChecks.enabled | quote }}
          - name: DD_EXTRA_CONFIG_PROVIDERS
            value: "kube_endpoints kube_services"
          - name: DD_EXTRA_LISTENERS
            value: "kube_endpoints kube_services"
          {{- end }}
          {{- if .Values.datadog.clusterName }}
          {{- if not (regexMatch "^([a-z]([a-z0-9\\-]{0,38}[a-z0-9])?\\.)*([a-z]([a-z0-9\\-]{0,38}[a-z0-9])?)$" .Values.datadog.clusterName) }}
          {{- fail "Your `clusterName` isn’t valid. It must be dot-separated tokens where a token start with a lowercase letter followed by up to 39 lowercase letters, numbers, or hyphens and cannot end with a hyphen."}}
          {{- end}}
          - name: DD_CLUSTER_NAME
            value: {{ .Values.datadog.clusterName | quote }}
          {{- end }}
          {{- if .Values.datadog.site }}
          - name: DD_SITE
            value: {{ .Values.datadog.site | quote }}
          {{- end }}
          {{- if .Values.datadog.dd_url }}
          - name: DD_DD_URL
            value: {{ .Values.datadog.dd_url | quote }}
          {{- end }}
          {{- if .Values.datadog.logLevel }}
          - name: DD_LOG_LEVEL
            value: {{ .Values.datadog.logLevel | quote }}
          {{- end }}
          - name: DD_LEADER_ELECTION
            value: {{ default "true" .Values.datadog.leaderElection | quote}}
          {{- if .Values.datadog.leaderLeaseDuration }}
          - name: DD_LEADER_LEASE_DURATION
            value: {{ .Values.datadog.leaderLeaseDuration | quote }}
          {{- else if .Values.datadog.clusterChecks.enabled }}
          - name: DD_LEADER_LEASE_DURATION
            value: "15"
          {{- end }}
          {{- if .Values.datadog.collectEvents }}
          - name: DD_COLLECT_KUBERNETES_EVENTS
            value: {{ .Values.datadog.collectEvents | quote}}
          {{- end }}
          - name: DD_CLUSTER_AGENT_KUBERNETES_SERVICE_NAME
            value: {{ template "datadog.fullname" . }}-cluster-agent
          - name: DD_CLUSTER_AGENT_AUTH_TOKEN
            valueFrom:
              secretKeyRef:
                name: {{ template "clusterAgent.tokenSecretName" . }}
                key: token
          - name: DD_KUBE_RESOURCES_NAMESPACE
            value: {{ .Release.Namespace }}
          {{- if .Values.datadog.orchestratorExplorer.enabled }}
          - name: DD_ORCHESTRATOR_EXPLORER_ENABLED
            value: "true"
          {{- end }}
{{- if .Values.clusterAgent.env }}
{{ toYaml .Values.clusterAgent.env | indent 10 }}
{{- end }}
        livenessProbe:
{{ toYaml .Values.clusterAgent.livenessProbe | indent 10 }}
        readinessProbe:
{{ toYaml .Values.clusterAgent.readinessProbe | indent 10 }}
        volumeMounts:
{{- if .Values.clusterAgent.volumeMounts }}
{{ toYaml .Values.clusterAgent.volumeMounts | indent 10 }}
{{- end }}
{{- if .Values.clusterAgent.confd }}
          - name: confd
            mountPath: /conf.d
            readOnly: true
{{- end }}
{{- if .Values.clusterAgent.datadog_cluster_yaml }}
          - name: cluster-agent-yaml
            mountPath: /etc/datadog-agent/datadog-cluster.yaml
            subPath: datadog-cluster.yaml
            readOnly: true
{{- end}}
      volumes:
{{- if .Values.clusterAgent.confd }}
        - name: confd
          configMap:
            name: {{ template "datadog.fullname" . }}-cluster-agent-confd
{{- end }}
{{- if .Values.clusterAgent.datadog_cluster_yaml }}
        - name: cluster-agent-yaml
          configMap:
            name: {{ template "datadog.fullname" . }}-cluster-agent-config
{{- end}}

{{- if .Values.clusterAgent.volumes }}
{{ toYaml .Values.clusterAgent.volumes | indent 8 }}
{{- end }}
      {{- if .Values.clusterAgent.tolerations }}
      tolerations:
{{ toYaml .Values.clusterAgent.tolerations | indent 8 }}
      {{- end }}
      {{- if .Values.clusterAgent.affinity }}
      affinity:
{{ toYaml .Values.clusterAgent.affinity | indent 8 }}
      {{- end }}
      nodeSelector:
        {{ template "label.os" . }}: {{ .Values.targetSystem }}
      {{- if .Values.clusterAgent.nodeSelector }}
{{ toYaml .Values.clusterAgent.nodeSelector | indent 8 }}
      {{- end }}
{{ end }}
