{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

apiVersion: {{ include "common.capabilities.deployment.apiVersion" . }}
kind: Deployment
metadata:
  name: {{ template "appsmith.backend.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/component: backend
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  replicas: {{ .Values.backend.replicaCount }}
  {{- if .Values.backend.updateStrategy }}
  strategy: {{- toYaml .Values.backend.updateStrategy | nindent 4 }}
  {{- end }}
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.backend.podLabels .Values.commonLabels ) "context" . ) }}
  selector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/component: backend
  template:
    metadata:
      {{- if .Values.backend.podAnnotations }}
      annotations: {{- include "common.tplvalues.render" (dict "value" .Values.backend.podAnnotations "context" $) | nindent 8 }}
      {{- end }}
      labels: {{- include "common.labels.standard" ( dict "customLabels" $podLabels "context" $ ) | nindent 8 }}
        app.kubernetes.io/component: backend
    spec:
      serviceAccountName: {{ template "appsmith.serviceAccountName" . }}
      {{- include "appsmith.imagePullSecrets" . | nindent 6 }}
      automountServiceAccountToken: {{ .Values.backend.automountServiceAccountToken }}
      {{- if .Values.backend.hostAliases }}
      hostAliases: {{- include "common.tplvalues.render" (dict "value" .Values.backend.hostAliases "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.backend.affinity }}
      affinity: {{- include "common.tplvalues.render" ( dict "value" .Values.backend.affinity "context" $) | nindent 8 }}
      {{- else }}
      affinity:
        podAffinity: {{- include "common.affinities.pods" (dict "type" .Values.backend.podAffinityPreset "component" "backend" "customLabels" $podLabels "context" $) | nindent 10 }}
        podAntiAffinity: {{- include "common.affinities.pods" (dict "type" .Values.backend.podAntiAffinityPreset "component" "backend" "customLabels" $podLabels "context" $) | nindent 10 }}
        nodeAffinity: {{- include "common.affinities.nodes" (dict "type" .Values.backend.nodeAffinityPreset.type "key" .Values.backend.nodeAffinityPreset.key "values" .Values.backend.nodeAffinityPreset.values) | nindent 10 }}
      {{- end }}
      {{- if .Values.backend.nodeSelector }}
      nodeSelector: {{- include "common.tplvalues.render" ( dict "value" .Values.backend.nodeSelector "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.backend.tolerations }}
      tolerations: {{- include "common.tplvalues.render" (dict "value" .Values.backend.tolerations "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.backend.priorityClassName }}
      priorityClassName: {{ .Values.backend.priorityClassName | quote }}
      {{- end }}
      {{- if .Values.backend.schedulerName }}
      schedulerName: {{ .Values.backend.schedulerName | quote }}
      {{- end }}
      {{- if .Values.backend.topologySpreadConstraints }}
      topologySpreadConstraints: {{- include "common.tplvalues.render" (dict "value" .Values.backend.topologySpreadConstraints "context" .) | nindent 8 }}
      {{- end }}
      {{- if .Values.backend.podSecurityContext.enabled }}
      securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.backend.podSecurityContext "context" $) | nindent 8 }}
      {{- end }}
      {{- if .Values.backend.terminationGracePeriodSeconds }}
      terminationGracePeriodSeconds: {{ .Values.backend.terminationGracePeriodSeconds }}
      {{- end }}
      initContainers:
        {{- if and .Values.volumePermissions.enabled .Values.backend.containerSecurityContext.enabled }}
        - name: volume-permissions
          image: {{ include "appsmith.volumePermissions.image" . }}
          imagePullPolicy: {{ .Values.volumePermissions.image.pullPolicy | quote }}
          command:
            - sh
            - -c
            - |
              mkdir -p {{ .Values.backend.persistence.mountPath }}
              find {{ .Values.backend.persistence.mountPath }} -mindepth 1 -maxdepth 1 -not -name ".snapshot" -not -name "lost+found" | xargs chown -R {{ .Values.backend.containerSecurityContext.runAsUser }}:{{ .Values.backend.podSecurityContext.fsGroup }}
          securityContext:
            runAsUser: 0
          {{- if .Values.volumePermissions.resources }}
          resources: {{- toYaml .Values.volumePermissions.resources | nindent 12 }}
          {{- else if ne .Values.volumePermissions.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.volumePermissions.resourcesPreset) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: data
              mountPath: {{ .Values.backend.persistence.mountPath }}
              subPath: {{ .Values.backend.persistence.subPath }}
        {{- end }}
        - name: preserve-logs-symlinks
          image: {{ include "appsmith.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy | quote }}
          {{- if .Values.backend.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.backend.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.backend.resources }}
          resources: {{- toYaml .Values.backend.resources | nindent 12 }}
          {{- else if ne .Values.backend.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.backend.resourcesPreset) | nindent 12 }}
          {{- end }}
          command:
            - /bin/bash
          args:
            - -ec
            - |
              #!/bin/bash
              . /opt/bitnami/scripts/libfs.sh
              # We copy the logs folder because it has symlinks to stdout and stderr
              if ! is_dir_empty /opt/bitnami/nginx/logs; then
                cp -r /opt/bitnami/nginx/logs /emptydir/nginx-logs-dir
              fi
          volumeMounts:
            - name: empty-dir
              mountPath: /emptydir
        {{- if not .Values.diagnosticMode.enabled }}
        {{- include "appsmith.waitForDBInitContainer" . | nindent 8 }}
        {{- end }}
        {{- if .Values.backend.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.backend.initContainers "context" $) | nindent 8 }}
        {{- end }}
      containers:
        - name: appsmith
          image: {{ template "appsmith.image" . }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          {{- if .Values.backend.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.backend.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.backend.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.backend.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.backend.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.backend.args "context" $) | nindent 12 }}
          {{- end }}
          env:
            - name: BITNAMI_DEBUG
              value: {{ ternary "true" "false" (or .Values.image.debug .Values.diagnosticMode.enabled) | quote }}
            - name: APPSMITH_MODE
              value: "backend"
            - name: APPSMITH_USERNAME
              value: {{ .Values.backend.adminUser | quote }}
            - name: APPSMITH_EMAIL
              value: {{ .Values.backend.adminEmail | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: APPSMITH_PASSWORD_FILE
              value: {{ printf "/secrets/%s" (include "appsmith.backend.password.secretKey" .) }}
            - name: APPSMITH_ENCRYPTION_PASSWORD_FILE
              value: {{ printf "/secrets/%s" (include "appsmith.backend.encryptionPassword.secretKey" .) }}
            - name: APPSMITH_ENCRYPTION_SALT_FILE
              value: {{ printf "/secrets/%s" (include "appsmith.backend.encryptionSalt.secretKey" .) }}
            {{- else }}
            - name: APPSMITH_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "appsmith.backend.secretName" . }}
                  key: {{ include "appsmith.backend.password.secretKey" . }}
            - name: APPSMITH_ENCRYPTION_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "appsmith.backend.secretName" . }}
                  key: {{ include "appsmith.backend.encryptionPassword.secretKey" . }}
            - name: APPSMITH_ENCRYPTION_SALT
              valueFrom:
                secretKeyRef:
                  name: {{ include "appsmith.backend.secretName" . }}
                  key: {{ include "appsmith.backend.encryptionSalt.secretKey" . }}
            {{- end }}
            - name: APPSMITH_DATABASE_HOST
              value: {{ include "appsmith.mongodb.hosts" . | quote }}
            - name: APPSMITH_DATABASE_PORT_NUMBER
              value: {{ include "appsmith.mongodb.port" . | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: APPSMITH_DATABASE_PASSWORD_FILE
              value: {{ printf "/secrets/%s" (include "appsmith.mongodb.secretKey" .) }}
            {{- else }}
            - name: APPSMITH_DATABASE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "appsmith.mongodb.secretName" . }}
                  key: {{ include "appsmith.mongodb.secretKey" . }}
            {{- end }}
            - name: APPSMITH_DATABASE_USER
              value: {{ ternary (index .Values.mongodb.auth.usernames 0) .Values.externalDatabase.username .Values.mongodb.enabled | quote }}
            - name: APPSMITH_DATABASE_NAME
              value: {{ ternary (index .Values.mongodb.auth.databases 0) .Values.externalDatabase.database .Values.mongodb.enabled | quote }}
            - name: APPSMITH_API_PORT
              value: {{ .Values.backend.containerPorts.http | quote }}
            - name: APPSMITH_REDIS_HOST
              value: {{ include "appsmith.redis.host" . | quote }}
            - name: APPSMITH_REDIS_PORT_NUMBER
              value: {{ include "appsmith.redis.port" . | quote }}
            {{- if .Values.usePasswordFiles }}
            - name: APPSMITH_REDIS_PASSWORD_FILE
              value: {{ printf "/secrets/%s" (include "appsmith.redis.secretKey" .) }}
            {{- else }}
            - name: APPSMITH_REDIS_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "appsmith.redis.secretName" . }}
                  key: {{ include "appsmith.redis.secretKey" . }}
            {{- end }}
            - name: APPSMITH_RTS_PORT
              value: {{ .Values.rts.containerPorts.http | quote }}
            {{- if .Values.backend.persistence.gitDataPath }}
            - name: APPSMITH_GIT_ROOT
              value: {{ include "appsmith.gitDataPath" . }}
            {{- end }}
            {{- if .Values.backend.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.backend.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            {{- if .Values.backend.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.backend.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.backend.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.backend.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- if .Values.backend.resources }}
          resources: {{- toYaml .Values.backend.resources | nindent 12 }}
          {{- else if ne .Values.backend.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.backend.resourcesPreset) | nindent 12 }}
          {{- end }}
          ports:
            - name: http
              containerPort: {{ .Values.backend.containerPorts.http }}
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.backend.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.backend.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.backend.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.backend.livenessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: http
          {{- end }}
          {{- if .Values.backend.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.backend.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.backend.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.backend.readinessProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /api/v1/health
              port: http
          {{- end }}
          {{- if .Values.backend.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.backend.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.backend.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.backend.startupProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /api/v1/health
              port: http
          {{- end }}
          {{- end }}
          {{- if .Values.backend.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.backend.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: empty-dir
              mountPath: /opt/bitnami/appsmith/conf
              subPath: app-conf-dir
            - name: empty-dir
              mountPath: /opt/bitnami/appsmith/logs
              subPath: app-logs-dir
            - name: empty-dir
              mountPath: /opt/bitnami/appsmith/tmp
              subPath: app-tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/nginx/conf
              subPath: nginx-conf-dir
            - name: empty-dir
              mountPath: /certs
              subPath: nginx-certs-dir
            - name: empty-dir
              mountPath: /opt/bitnami/nginx/tmp
              subPath: nginx-tmp-dir
            - name: empty-dir
              mountPath: /opt/bitnami/nginx/logs
              subPath: nginx-logs-dir
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            {{- if .Values.usePasswordFiles }}
            - name: appsmith-secrets
              mountPath: /secrets
            {{- end }}
            - name: data
              mountPath: {{ .Values.backend.persistence.mountPath }}
              {{- if .Values.backend.persistence.subPath }}
              subPath: {{ .Values.backend.persistence.subPath }}
              {{- end }}
            {{- if .Values.backend.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.backend.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
        - name: rts-redirect
          image: {{ template "appsmith.redirect.image" . }}
          imagePullPolicy: {{ .Values.backend.redirectAmbassador.image.pullPolicy }}
          {{- if .Values.backend.redirectAmbassador.containerSecurityContext.enabled }}
          securityContext: {{- include "common.compatibility.renderSecurityContext" (dict "secContext" .Values.backend.redirectAmbassador.containerSecurityContext "context" $) | nindent 12 }}
          {{- end }}
          {{- if .Values.diagnosticMode.enabled }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.diagnosticMode.command "context" $) | nindent 12 }}
          {{- else if .Values.backend.redirectAmbassador.command }}
          command: {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.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.backend.redirectAmbassador.args }}
          args: {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.args "context" $) | nindent 12 }}
          {{- end }}
          env:
            {{- if .Values.backend.redirectAmbassador.extraEnvVars }}
            {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.extraEnvVars "context" $) | nindent 12 }}
            {{- end }}
          envFrom:
            {{- if .Values.backend.redirectAmbassador.extraEnvVarsCM }}
            - configMapRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.extraEnvVarsCM "context" $) }}
            {{- end }}
            {{- if .Values.backend.redirectAmbassador.extraEnvVarsSecret }}
            - secretRef:
                name: {{ include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.extraEnvVarsSecret "context" $) }}
            {{- end }}
          {{- if .Values.backend.redirectAmbassador.resources }}
          resources: {{- toYaml .Values.backend.redirectAmbassador.resources | nindent 12 }}
          {{- else if ne .Values.backend.redirectAmbassador.resourcesPreset "none" }}
          resources: {{- include "common.resources.preset" (dict "type" .Values.backend.redirectAmbassador.resourcesPreset) | nindent 12 }}
          {{- end }}
          ports:
            # This port needs to be hardcoded because of Appsmith code
            # https://github.com/appsmithorg/appsmith/blob/021b4177eac01a445cacf8bfb4688de449366701/app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonConfig.java#L136
            - name: http-redirect
              containerPort: 8080
          {{- if not .Values.diagnosticMode.enabled }}
          {{- if .Values.backend.redirectAmbassador.customLivenessProbe }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.customLivenessProbe "context" $) | nindent 12 }}
          {{- else if .Values.backend.redirectAmbassador.livenessProbe.enabled }}
          livenessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.backend.redirectAmbassador.livenessProbe "enabled") "context" $) | nindent 12 }}
            tcpSocket:
              port: http-redirect
          {{- end }}
          {{- if .Values.backend.redirectAmbassador.customReadinessProbe }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.customReadinessProbe "context" $) | nindent 12 }}
          {{- else if .Values.backend.redirectAmbassador.readinessProbe.enabled }}
          readinessProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.backend.redirectAmbassador.readinessProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /rts-api/v1/health-check
              port: http-redirect
          {{- end }}
          {{- if .Values.backend.redirectAmbassador.customStartupProbe }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.customStartupProbe "context" $) | nindent 12 }}
          {{- else if .Values.backend.redirectAmbassador.startupProbe.enabled }}
          startupProbe: {{- include "common.tplvalues.render" (dict "value" (omit .Values.backend.redirectAmbassador.startupProbe "enabled") "context" $) | nindent 12 }}
            httpGet:
              path: /rts-api/v1/health-check
              port: http-redirect
          {{- end }}
          {{- end }}
          {{- if .Values.backend.redirectAmbassador.lifecycleHooks }}
          lifecycle: {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.lifecycleHooks "context" $) | nindent 12 }}
          {{- end }}
          volumeMounts:
            - name: haproxy-conf
              mountPath: /bitnami/haproxy/conf
            - name: empty-dir
              mountPath: /tmp
              subPath: tmp-dir
            {{- if .Values.backend.redirectAmbassador.extraVolumeMounts }}
            {{- include "common.tplvalues.render" (dict "value" .Values.backend.redirectAmbassador.extraVolumeMounts "context" $) | nindent 12 }}
            {{- end }}
        {{- if .Values.backend.sidecars }}
        {{- include "common.tplvalues.render" ( dict "value" .Values.backend.sidecars "context" $) | nindent 8 }}
        {{- end }}
      volumes:
        - name: empty-dir
          emptyDir: {}
        - name: haproxy-conf
          configMap:
            name: {{ include "appsmith.redirect.fullname" . }}
        {{- if .Values.usePasswordFiles }}
        - name: appsmith-secrets
          projected:
            sources:
              - secret:
                  name:  {{ include "appsmith.backend.secretName" . }}
              - secret:
                  name:  {{ include "appsmith.mongodb.secretName" . }}
              - secret:
                  name:  {{ include "appsmith.redis.secretName" . }}
        {{- end }}
        - name: data
        {{- if .Values.backend.persistence.enabled }}
          persistentVolumeClaim:
            claimName: {{ default (include "appsmith.backend.fullname" .) .Values.backend.persistence.existingClaim }}
        {{- else }}
          emptyDir: {}
        {{- end }}
        {{- if .Values.backend.extraVolumes }}
        {{- include "common.tplvalues.render" (dict "value" .Values.backend.extraVolumes "context" $) | nindent 8 }}
        {{- end }}
