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

{{- $sequencerLabel := (printf "%s-sequencer" .Release.Name) }}

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    {{- include "splice-util-lib.default-labels" (set . "app" $sequencerLabel) | nindent 4 }}
    splice-component: sequencer
    app.kubernetes.io/component: sequencer
  name: {{ .Release.Name }}-sequencer
  namespace: {{ .Release.Namespace }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ $sequencerLabel }}
  strategy:
    type: Recreate
  template:
    metadata:
      annotations:
        {{- toYaml .Values.pod.annotations | nindent 8 }}
      labels:
        {{- include "splice-util-lib.default-labels" (set . "app" $sequencerLabel) | nindent 8 }}
        splice-component: sequencer
        app.kubernetes.io/component: sequencer
        {{- with $.Values.metrics.migration }}
        migration_id: {{ .id | quote }}
        {{- end }}
    spec:
      {{- include "splice-util-lib.service-account" .Values | nindent 6 }}
      containers:
        - name: sequencer
        {{- if eq .Values.sequencer.driver.type "cometbft"}}
          image: "{{ .Values.imageRepo }}/canton-cometbft-sequencer:{{ .Chart.AppVersion }}{{ ((.Values.imageDigests).canton_cometbft_sequencer) }}"
        {{- else}}
          image: "{{ .Values.imageRepo }}/canton-sequencer:{{ .Chart.AppVersion }}{{ ((.Values.imageDigests).canton_sequencer) }}"
        {{- end}}
          env:
            - name: JAVA_TOOL_OPTIONS
              value: {{ .Values.defaultJvmOptions }} {{ .Values.additionalJvmOptions }}
            - name: CANTON_DOMAIN_POSTGRES_SERVER
              value: {{ .Values.sequencer.persistence.host }}
            - name: CANTON_DOMAIN_POSTGRES_PORT
              value: {{ .Values.sequencer.persistence.port | quote }}
            - name: CANTON_DOMAIN_POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.sequencer.persistence.secretName }}
                  key: postgresPassword
        {{- if .Values.sequencer.persistence.databaseName }}
            - name: CANTON_SEQUENCER_POSTGRES_DB
              value: {{ .Values.sequencer.persistence.databaseName }}
        {{- end }}
        {{- if eq .Values.sequencer.driver.type "postgres"}}
            - name: ADDITIONAL_CONFIG_SEQUENCER_DRIVER_REFERENCE
              value: |
                canton.sequencers.sequencer.sequencer {
                  config {
                    storage = ${_storage}
                    storage.config.properties.serverName = ${?SEQUENCER_DRIVER_DATABASE_ADDRESS}
                    storage.config.properties.password = ${?SEQUENCER_DRIVER_DATABASE_PASSWORD}
                    storage.config.properties.currentSchema = "sequencer_driver"
                    storage.config.properties.databaseName = ${?CANTON_SEQUENCER_POSTGRES_DB}
                  }
                  type = "reference"
                }
            - name: SEQUENCER_DRIVER_DATABASE_ADDRESS
              value: {{ .Values.sequencer.driver.address }}
            - name: SEQUENCER_DRIVER_DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.sequencer.persistence.secretName }}
                  key: postgresPassword
        {{- else if eq .Values.sequencer.driver.type "cometbft"}}
            - name: ADDITIONAL_CONFIG_SEQUENCER_DRIVER_COMETBFT
              value: |
                canton.sequencers.sequencer.sequencer {
                  config {
                    cometbft-node-host = {{ .Values.sequencer.driver.host }}
                    cometbft-node-port = {{ .Values.sequencer.driver.port }}
                    health-check-attempts = 100000
                  }
                  type = "CometBFT"
                }
        {{- else if eq .Values.sequencer.driver.type "cantonbft"}}
            # TODO(#930) - use a different database for the bft storage
            - name: ADDITIONAL_CONFIG_SEQUENCER_DRIVER_BFT
              value: |
                canton.sequencers.sequencer.sequencer {
                  config {
                    storage = ${_storage}
                    storage.config.properties.serverName = ${?CANTON_DOMAIN_POSTGRES_SERVER}
                    storage.config.properties.password = ${?CANTON_DOMAIN_POSTGRES_PASSWORD}
                    storage.config.properties.currentSchema = "sequencer"
                    storage.config.properties.databaseName = ${?CANTON_SEQUENCER_POSTGRES_DB}
                    initial-network {
                      endpoint-authentication {
                        enabled = true
                      }
                      server-endpoint {
                        address="0.0.0.0"
                        port=5010
                        external-address="{{ .Values.sequencer.driver.externalAddress }}"
                        external-port={{ .Values.sequencer.driver.externalPort }}
                      }
                      peer-endpoints = []
                    }
                  }
                  type = "BFT"
                }
        {{- end}}
            {{- with .Values.sequencer.tokenExpirationTime }}
            - name: SEQUENCER_TOKEN_EXPIRATION_TIME
              value: "{{ . }}"
            {{- end }}
            {{- include "splice-util-lib.additional-env-vars" .Values.additionalEnvVars | indent 12}}
            {{- include "splice-util-lib.additional-env-vars" .Values.sequencer.additionalEnvVars | indent 12}}
            {{- include "splice-util-lib.log-level" .Values | indent 12}}
          {{- with .Values.imagePullPolicy }}
          imagePullPolicy: {{ . }}
          {{- end }}
          ports:
            - containerPort: 5008
              name: cs-pub-api
              protocol: TCP
            - containerPort: 5009
              name: cs-adm-api
              protocol: TCP
        {{- if .Values.sequencer.resources }}
          resources: {{- toYaml .Values.sequencer.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: sequencer-volume
              mountPath: /persistent-data
          {{- end }}
      restartPolicy: Always
      initContainers:
        - name: pg-init
          image: postgres:14
          env:
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  key: postgresPassword
                  name: {{ .Values.sequencer.persistence.secretName }}
          command:
            - 'bash'
            - '-c'
            - |
              until errmsg=$(psql -h {{ .Values.sequencer.persistence.host }} -p {{ .Values.sequencer.persistence.port }} --username=cnadmin --dbname=cantonnet -c 'create database {{ .Values.sequencer.persistence.databaseName }}' 2>&1); do
                if [[ $errmsg == *"already exists"* ]]; then
                  echo "Database {{ .Values.sequencer.persistence.databaseName }} already exists. Done."
                  break
                fi

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