# Copyright (c) 2024 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

{{- $mediatorLabel := (printf "%s-mediator" .Release.Name) }}

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    {{- include "splice-util-lib.default-labels" (set . "app" $mediatorLabel) | nindent 4 }}
    splice-component: mediator
    app.kubernetes.io/component: mediator
    {{- with $.Values.metrics.migration }}
    migration_id: {{ .id | quote }}
    {{- end }}
  name: {{ $mediatorLabel }}
  namespace: {{ .Release.Namespace }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ $mediatorLabel }}
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        {{- toYaml .Values.pod.annotations | nindent 8 }}
      labels:
        {{- include "splice-util-lib.default-labels" (set . "app" $mediatorLabel) | nindent 8 }}
        splice-component: mediator
        app.kubernetes.io/component: mediator
        {{- with $.Values.metrics.migration }}
        migration_id: {{ .id | quote }}
        {{- end }}
    spec:
      {{- include "splice-util-lib.service-account" .Values | nindent 6 }}
      containers:
      - name: mediator
        image: "{{ .Values.imageRepo }}/canton-mediator:{{ .Chart.AppVersion }}{{ ((.Values.imageDigests).canton_mediator) }}"
        env:
        - name: JAVA_TOOL_OPTIONS
          value: {{ .Values.defaultJvmOptions }} {{ .Values.additionalJvmOptions }}
        - name: CANTON_DOMAIN_POSTGRES_SERVER
          value: {{ .Values.mediator.persistence.host }}
        - name: CANTON_DOMAIN_POSTGRES_PORT
          value: {{ .Values.mediator.persistence.port | quote }}
        - name: CANTON_DOMAIN_POSTGRES_PASSWORD
          valueFrom:
           secretKeyRef:
              name: {{ .Values.mediator.persistence.secretName }}
              key: postgresPassword
        {{- if .Values.mediator.persistence.databaseName }}
        - name: CANTON_MEDIATOR_POSTGRES_DB
          value: {{ .Values.mediator.persistence.databaseName }}
        {{- end }}
        {{- include "splice-util-lib.additional-env-vars" .Values.additionalEnvVars | indent 8}}
        {{- include "splice-util-lib.additional-env-vars" .Values.mediator.additionalEnvVars | indent 8}}
        {{- include "splice-util-lib.log-level" .Values | indent 8}}
        {{- with .Values.imagePullPolicy }}
        imagePullPolicy: {{ . }}
        {{- end }}
        ports:
        - containerPort: 5007
          name: cm-adm-api
          protocol: TCP
        - containerPort: 10013
          name: cm-metrics
          protocol: TCP
      {{- if .Values.mediator.resources }}
        resources: {{- toYaml .Values.mediator.resources | nindent 12 }}
        {{- else }}
        {{- with .Values.resources }}
        resources: {{- toYaml . | nindent 12 }}
        {{- end }}
      {{- end }}
        {{- if .Values.enableHealthProbes }}
        livenessProbe:
          grpc:
            port: 5061
            service: liveness
          initialDelaySeconds: {{ .Values.livenessProbeInitialDelaySeconds | default 600 }}
          periodSeconds: 60
          failureThreshold: 5
          timeoutSeconds: 10
        readinessProbe:
          grpc:
            port: 5061
          initialDelaySeconds: 5
          periodSeconds: 5
          failureThreshold: 3
          timeoutSeconds: 10
        {{- end }}
        {{- if .Values.pvc }}
        volumeMounts:
          - name: mediator-volume
            mountPath: /persistent-data
        {{- end }}
      restartPolicy: Always
      initContainers:
        - name: pg-init
          image: postgres:14
          env:
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  key: postgresPassword
                  name: {{ .Values.mediator.persistence.secretName }}
          command:
            - 'bash'
            - '-c'
            - |
              until errmsg=$(psql -h {{ .Values.mediator.persistence.host }} -p {{ .Values.mediator.persistence.port }} --username=cnadmin --dbname=cantonnet -c 'create database {{ .Values.mediator.persistence.databaseName }}' 2>&1); do
                if [[ $errmsg == *"already exists"* ]]; then
                  echo "Database {{ .Values.mediator.persistence.databaseName }} already exists. Done."
                  break
                fi

                echo "trying to create postgres database {{ .Values.mediator.persistence.databaseName }}, last error: $errmsg";
                sleep 2;
              done
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      volumes:
      {{- if .Values.pvc }}
        - name: mediator-volume
          persistentVolumeClaim:
            claimName: {{ .Release.Name }}-mediator-pvc
      {{- end }}
---
{{-  if .Values.pvc }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: {{ .Release.Name }}-mediator-pvc
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "splice-util-lib.default-labels" (set . "app" $mediatorLabel) | nindent 4 }}
  annotations:
    helm.sh/resource-policy: keep
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: {{ .Values.pvc.size }}
  storageClassName: {{ .Values.pvc.volumeStorageClass }}
{{- end }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ $mediatorLabel }}
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "splice-util-lib.default-labels" (set . "app" $mediatorLabel) | nindent 4 }}
    {{- with $.Values.metrics.migration }}
    migration_id: {{ .id | quote }}
    {{- end }}
spec:
  selector:
    app: {{ $mediatorLabel }}
  ports:
  - name: cm-adm-api
    port: 5007
    protocol: TCP
  - name: cm-metrics
    port: 10013
    protocol: TCP
---
{{- if .Values.enablePostgresMetrics }}
{{- include "splice-util-lib.postgres-metrics" (dict "persistence" .Values.mediator.persistence "namespace" .Release.Namespace "nodeSelector" .Values.nodeSelector "affinity" .Values.affinity "tolerations" .Values.tolerations ) }}
{{- end}}
