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

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    {{- include "splice-util-lib.default-labels" (set . "app" .Release.Name) | nindent 4 }}
    {{- with $.Values.metrics.migration }}
    migration_id: {{ .id | quote }}
    {{- end }}
  name: {{ .Release.Name }}
  namespace: {{ .Release.Namespace }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ .Release.Name }}
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        {{- toYaml .Values.pod.annotations | nindent 8 }}
      labels:
        {{- include "splice-util-lib.default-labels" (set . "app" .Release.Name) | nindent 8 }}
        {{- with $.Values.metrics.migration }}
        migration_id: {{ .id | quote }}
        {{- end }}
    spec:
      {{- include "splice-util-lib.service-account" .Values | nindent 6 }}
      securityContext:
        runAsUser: 1001
        runAsGroup: 1001
        fsGroup: 1001
      containers:
      - name: participant
        image: "{{ .Values.imageRepo }}/canton-participant:{{ .Chart.AppVersion }}{{ ((.Values.imageDigests).canton_participant) }}"
        {{- with .Values.imagePullPolicy }}
        imagePullPolicy: {{ . }}
        {{- end }}
        env:
        - name: JAVA_TOOL_OPTIONS
          value: {{ .Values.defaultJvmOptions }} {{ .Values.additionalJvmOptions }}
        - name: CANTON_PARTICIPANT_POSTGRES_SERVER
          value: {{ .Values.persistence.host }}
        - name: CANTON_PARTICIPANT_POSTGRES_PORT
          value: {{ .Values.persistence.port | quote }}
        - name: CANTON_PARTICIPANT_POSTGRES_SCHEMA
          value: {{ .Values.persistence.schema }}
        - name: CANTON_PARTICIPANT_POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ .Values.persistence.secretName }}
              key: postgresPassword
        {{- if .Values.persistence.databaseName }}
        - name: CANTON_PARTICIPANT_POSTGRES_DB
          value: {{ .Values.persistence.databaseName }}
        {{- end }}
        {{- if .Values.jsonApiServerPathPrefix }}
        - name: CANTON_PARTICIPANT_JSON_API_SERVER_PATH_PREFIX
          value: {{ .Values.jsonApiServerPathPrefix }}
        {{- end }}
        {{- if .Values.kms }}
        - name: ADDITIONAL_CONFIG_SPLICE_PARTICIPANT_CRYPTO_PROVIDER_KMS
          value: |
            canton.participants.participant.crypto {
              provider = kms
              kms = {
                {{- include "splice-util-lib.render-nested-config" .Values.kms | trim | nindent 16 }}
              }
            }
        {{- end }}
        {{- if .Values.disableAuth }}
        - name: CANTON_PARTICIPANT_ADMIN_USER_NAME
          value: ledger-api-user
        - name: ADDITIONAL_CONFIG_DISABLE_AUTH
          value: |
            canton.participants.participant.ledger-api.auth-services=[{
              type = unsafe-jwt-hmac-256
              target-audience = "https://ledger_api.example.com"
              secret = "unsafe"
            }]
        {{- else }}
        - name: CANTON_PARTICIPANT_ADMIN_USER_NAME
          valueFrom: {{ .Values.participantAdminUserNameFrom | toYaml | nindent 12 }}
        - name: AUTH_JWKS_URL
          value: {{ .Values.auth.jwksUrl }}
        - name: AUTH_TARGET_AUDIENCE
          value: {{ .Values.auth.targetAudience }}
        {{- end }}
        {{- include "splice-util-lib.additional-env-vars" .Values.additionalEnvVars | indent 8}}
        {{- include "splice-util-lib.log-level" .Values | indent 8}}
        ports:
        - containerPort: 5002
          name: lg-adm-api
          protocol: TCP
        - containerPort: 5001
          name: lg-api
          protocol: TCP
        - containerPort: 7575
          name: json-api
          protocol: TCP
        - containerPort: 10013
          name: metrics-api
          protocol: TCP
        {{- 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 }}
        {{- with .Values.resources }}
        resources: {{- toYaml . | nindent 10 }}
        {{- end }}
        {{- if and .Values.extraVolumeMounts (gt (len .Values.extraVolumeMounts) 0) }}
        volumeMounts:
          {{- range .Values.extraVolumeMounts }}
          - name: {{ .name }}
            mountPath: {{ .mountPath }}
            {{- if .subPath }}
            subPath: {{ .subPath }}
            {{- end }}
            {{- if .readOnly }}
            readOnly: {{ .readOnly }}
            {{- end }}
          {{- end }}
        {{- end }}
      {{- if or (.Values.persistence.enablePgInitContainer) (.Values.extraInitContainers) }}
      initContainers:
        {{- if .Values.persistence.enablePgInitContainer }}
        - name: pg-init
          image: postgres:14
          env:
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  key: postgresPassword
                  name: {{ .Values.persistence.secretName }}
          command:
            - 'bash'
            - '-c'
            - |
              until errmsg=$(psql -h {{ .Values.persistence.host }} -p {{ .Values.persistence.port }} --username=cnadmin --dbname=cantonnet -c 'create database {{ .Values.persistence.databaseName }}' 2>&1); do
                if [[ $errmsg == *"already exists"* ]]; then
                  echo "Database {{ .Values.persistence.databaseName }} already exists. Done."
                  break
                fi

                echo "trying to create postgres database {{ .Values.persistence.databaseName }}, last error: $errmsg";
                sleep 2;
              done
        {{- end }}
        {{- if .Values.extraInitContainers }}
        {{ .Values.extraInitContainers | toYaml | nindent 8 }}
        {{- end }}
      {{- end }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- if and .Values.extraVolumes (gt (len .Values.extraVolumes) 0) }}
      volumes:
        {{- range .Values.extraVolumes }}
        - name: {{ .name }}
          {{- if .secret }}
          secret:
            secretName: {{ .secret.secretName }}
          {{- end }}
          {{- if .persistentVolumeClaim }}
          persistentVolumeClaim:
            claimName: {{ .persistentVolumeClaim.claimName }}
          {{- end }}
        {{- end }}
      {{- end }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ .Release.Name }}
  namespace: {{ .Release.Namespace }}
  labels:
    {{- include "splice-util-lib.default-labels" (set . "app" .Release.Name) | nindent 4 }}
    {{- with $.Values.metrics.migration }}
    migration_id: {{ .id | quote }}
    {{- end }}
spec:
  selector:
    app: {{ .Release.Name }}
  ports:
  - name: lg-adm-api
    port: 5002
    protocol: TCP
  - name: lg-api
    port: 5001
    protocol: TCP
  - name: metrics
    port: 10013
    protocol: TCP
  - name: json-api
    port: 7575
    protocol: TCP
---
{{- if .Values.enablePostgresMetrics }}
{{- include "splice-util-lib.postgres-metrics" (dict "persistence" .Values.persistence "namespace" .Release.Namespace "nodeSelector" .Values.nodeSelector "affinity" .Values.affinity "tolerations" .Values.tolerations ) }}
{{- end}}
