{{- $serviceName := printf "%s-headless" (include "common.names.fullname" .) }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ $serviceName }}
  namespace: {{ include "names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    {{- if .Values.statefulsetLabels }}
    {{- include "common.tplvalues.render" (dict "value" .Values.statefulsetLabels "context" $) | nindent 4 }}
    {{- end }}
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  clusterIP: None
  selector:
    app: {{ include "common.names.fullname" . }}
---
apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
kind: StatefulSet
metadata:
  name: {{ include "common.names.fullname" . }}
  namespace: {{ include "names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    {{- if .Values.statefulsetLabels }}
    {{- include "common.tplvalues.render" (dict "value" .Values.statefulsetLabels "context" $) | nindent 4 }}
    {{- end }}
    {{- if .Values.commonLabels }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.commonLabels "context" $ ) | nindent 4 }}
    {{- end }}
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  serviceName: {{ $serviceName }}
  podManagementPolicy: {{ .Values.podManagementPolicy }}
  replicas: {{ .Values.replicaCount }}
  {{- if .Values.updateStrategy }}
  updateStrategy: {{- toYaml .Values.updateStrategy | nindent 4 }}
  {{- end }}
  selector:
    matchLabels:
      {{- include "common.labels.matchLabels" . | nindent 6 }}
      app: {{ include "common.names.fullname" . }}
  template:
    metadata:
      labels: {{- include "common.labels.standard" . | nindent 8 }}
        {{- if .Values.podLabels }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podLabels "context" $) | nindent 8 }}
        {{- end }}
        app: {{ include "common.names.fullname" . }}
      annotations:
        {{- if .Values.commonAnnotations }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 8 }}
        {{- end }}
        checksum/config: {{ include (print $.Template.BasePath "/configmaps.yaml") . | sha256sum }}
        checksum/secret: {{ include (print $.Template.BasePath "/secrets.yaml") . | sha256sum }}
        {{- if .Values.podAnnotations }}
        {{- include "common.tplvalues.render" (dict "value" .Values.podAnnotations "context" $) | nindent 8 }}
        {{- end }}
    spec:
      {{- if .Values.schedulerName }}
      schedulerName: {{ .Values.schedulerName | quote }}
      {{- end }}
      serviceAccountName: {{ template "names.serviceAccountName" . }}
      {{- if .Values.affinity }}
      affinity: {{- include "common.tplvalues.render" (dict "value" .Values.affinity "context" .) | nindent 8 }}
      {{- else }}
      affinity:
        {{- if .Values.podAffinityPreset }}
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAffinityPreset "context" $) | nindent 10 }}
        {{- end }}
        {{- if .Values.podAntiAffinityPreset }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.podAntiAffinityPreset "context" $) | nindent 10 }}
        {{- end }}
        {{- if .Values.nodeAffinityPreset.type }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.nodeAffinityPreset.type "key" .Values.nodeAffinityPreset.key "values" .Values.nodeAffinityPreset.values) | nindent 10 }}
        {{- end }}
      {{- end }}
      {{- if .Values.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" (dict "value" .Values.nodeSelector "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: {{ .Values.priorityClassName }}
      {{- end }}
      {{- if .Values.podSecurityContext.enabled }}
      securityContext: {{- omit .Values.podSecurityContext "enabled" | toYaml | nindent 8 }}
      {{- end }}
      {{- if .Values.dnsPolicy }}
      dnsPolicy: {{ .Values.dnsPolicy }}
      {{- end }}
      {{- if .Values.dnsConfig }}
      dnsConfig: {{- include "common.tplvalues.render" (dict "value" .Values.dnsConfig "context" .) | nindent 8 }}
      {{- end }}
      hostNetwork: {{ .Values.hostNetwork }}
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      {{- if (not (empty .Values.image.pullSecrets)) }}
      imagePullSecrets:
        {{- range .Values.image.pullSecrets }}
        - name: {{ . }}
        {{- end }}
      {{- end }}
      containers:
        - name: runner
          image: {{ include "images.image" (dict "imageRoot" .Values.image) }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.containerSecurityContext.enabled }}
          securityContext: {{- omit .Values.containerSecurityContext "enabled" | toYaml | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.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.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.args "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          env:
            - name: RELEASE_RUNNER_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: RELEASE_RUNNER_KUBERNETES_SERVICE_NAME
              value: {{ $serviceName }}
            - name: RELEASE_RUNNER_RELEASE_URL
              value: "{{ required "Use --set release.url=<value> to define the Digital.ai Release URL" .Values.release.url }}"
            - name: RELEASE_RUNNER_TOKEN
              valueFrom:
                secretKeyRef:
                  name: {{ include "common.names.fullname" . }}-registration-token
                  key: token
            - name: RELEASE_RUNNER_KUBERNETES_REGISTRY_MAPPING_SECRET_NAME
              value: {{ include "common.names.fullname" . }}-registry-mapping
            - name: RELEASE_RUNNER_CAPABILITIES
              value: {{ .Values.runner.capabilities }}
            - name: RELEASE_RUNNER_KUBERNETES_NAMESPACE
              value: {{ include "names.namespace" . | quote }}
            - name: RELEASE_RUNNER_PROFILE
              value: "{{ .Values.runner.activeProfiles }}"
            - name: RELEASE_RUNNER_KUBERNETES_IN_CLUSTER_CONFIG
              value: "true"
            - name: RELEASE_RUNNER_STORE_NAME
              value: "/workspace/db/runner-store.db"
            {{- if .Values.runner.truststore }}
            - name: RELEASE_RUNNER_REST_CLIENT_TRUSTSTORE
              value: "/workspace/truststore.p12"
            - name: RELEASE_RUNNER_REST_CLIENT_TRUSTSTORE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "common.names.fullname" . }}-truststore
                  key: password
            {{- end}}
            {{- if .Values.runner.restClientCA }}
            - name: RELEASE_RUNNER_REST_CLIENT_CA
              value: "/workspace/ca.pem"
            {{- end}}
            - name: RELEASE_RUNNER_KUBERNETES_PASSED_SA_ANNOTATIONS
              value: {{ .Values.runner.kubernetes.passedSaAnnotations }}
            {{- if .Values.executorSecurityContext }}
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_ENABLED
              value: "{{ .Values.executorSecurityContext.enabled }}"
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_RUN_AS_USER
              value: "{{ .Values.executorSecurityContext.runAsUser }}"
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_RUN_AS_GROUP
              value: "{{ .Values.executorSecurityContext.runAsGroup }}"
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_FS_GROUP
              value: "{{ .Values.executorSecurityContext.fsGroup }}"
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_RUN_AS_NON_ROOT
              value: "{{ .Values.executorSecurityContext.runAsNonRoot }}"
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_ALLOW_PRIVILEGE_ESCALATION
              value: "{{ .Values.executorSecurityContext.allowPrivilegeEscalation }}"
            - name: RELEASE_RUNNER_EXECUTOR_SECURITY_CONTEXT_READ_ONLY_ROOT_FILESYSTEM
              value: "{{ .Values.executorSecurityContext.readOnlyRootFilesystem }}"
            {{- end }}
            {{- if .Values.runner.executorLabels }}
            - name: RELEASE_RUNNER_KUBERNETES_EXECUTOR_LABELS
              value: {{ .Values.runner.executorLabels | toJson | quote }}
            {{- end }}
            {{- if .Values.runner.metadata.clusterName }}
            - name: RELEASE_RUNNER_METADATA_CLUSTER_NAME
              value: {{ .Values.runner.metadata.clusterName | quote }}
            {{- end }}
            {{- if .Values.runner.metadata.environment }}
            - name: RELEASE_RUNNER_METADATA_ENVIRONMENT
              value: {{ .Values.runner.metadata.environment | quote }}
            {{- end }}
            {{- if .Values.runner.metadata.dataCenter }}
            - name: RELEASE_RUNNER_METADATA_DATA_CENTER
              value: {{ .Values.runner.metadata.dataCenter | quote }}
            {{- end }}
            {{- if .Values.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            - configMapRef:
                name: {{ include "common.names.fullname" . }}-env-config
                optional: true
            {{- if .Values.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if and .Values.health.enabled (not .Values.hostNetwork) }}
          livenessProbe:
            httpGet:
              path: /live
              port: 8686
            initialDelaySeconds: {{ .Values.health.probesLivenessTimeout }}
            periodSeconds: {{ .Values.health.periodScans }}
            failureThreshold: {{ .Values.health.probeFailureThreshold }}
          readinessProbe:
            httpGet:
              path: /ready
              port: 8686
            initialDelaySeconds: {{ .Values.health.probesReadinessTimeout }}
            periodSeconds: {{ .Values.health.periodScans }}
            failureThreshold: {{ .Values.health.probeFailureThreshold }}
          {{- end }}
          {{- end }}
          {{- if .Values.resources }}
          resources: {{- toYaml .Values.resources | nindent 12 }}
          {{- end }}
          {{- if or .Values.runner.truststore .Values.runner.restClientCA .Values.extraVolumeMounts .Values.emptyDirPaths }}
          volumeMounts:
            {{- if .Values.runner.truststore }}
            - mountPath: /workspace/truststore.p12
              name: release-runner-truststore
              subPath: truststore.p12
              readOnly: true
            {{- end }}
            {{- if .Values.runner.restClientCA }}
            - mountPath: /workspace/ca.pem
              name: release-runner-rest-client-ca
              subPath: ca.pem
              readOnly: true
            {{- end }}
            {{- range $path := .Values.emptyDirPaths }}
            - name: empty-dir
              mountPath: {{ $path }}
              subPath: {{ regexFind "[^/]+$" $path }}
            {{- end }}
            {{- if .Values.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
          {{- end }}
      {{- if or .Values.runner.truststore .Values.runner.restClientCA .Values.extraVolumeMounts .Values.emptyDirPaths }}
      volumes:
        {{- if .Values.runner.truststore }}
        - name: release-runner-truststore
          secret:
            secretName: {{ include "common.names.fullname" . }}-truststore
        {{- end}}
        {{- if .Values.runner.restClientCA }}
        - name: release-runner-rest-client-ca
          secret:
            secretName: {{ include "common.names.fullname" . }}-rest-client-ca
        {{- end}}
        {{- if .Values.emptyDirPaths }}
        - name: empty-dir
          emptyDir: {}
        {{- end }}
        {{- if .Values.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.extraVolumes "context" $)  | nindent 8 }}
        {{- end }}
      {{- end }}
