apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "pinepods.fullname" . }}
  labels:
    {{- include "pinepods.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  strategy:
    type: Recreate  # Ensures clean volume handling
  selector:
    matchLabels:
      {{- include "pinepods.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "pinepods.selectorLabels" . | nindent 8 }}
        app.kubernetes.io/component: main
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{ .Values.service.port }}
              protocol: TCP
          envFrom:
            - secretRef:
                name: {{ include "pinepods.fullname" $ }}-env
          env:
            {{ if (and (not .Values.postgresql.enabled) (.Values.externalDatabase.existingSecret.enabled)) -}}
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .Values.externalDatabase.existingSecret.name }}
                  key: {{ .Values.externalDatabase.existingSecret.key }}
            {{- end }}
          volumeMounts:
            {{- if .Values.persistence.enabled }}
            - name: downloads
              mountPath: /opt/pinepods/downloads
            - name: backups
              mountPath: /opt/pinepods/backups
            {{- end }}
          livenessProbe:
            httpGet:
              path: /api/pinepods_check
              port: http
            initialDelaySeconds: 120
            periodSeconds: 30
            timeoutSeconds: 5
            successThreshold: 1
            failureThreshold: 3
          readinessProbe:
            httpGet:
              path: /api/pinepods_check
              port: http
            initialDelaySeconds: 120
            periodSeconds: 10
            timeoutSeconds: 5
            successThreshold: 1
            failureThreshold: 3
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
      volumes:
        {{- if .Values.persistence.enabled }}
        - name: downloads
          persistentVolumeClaim:
            claimName: {{ if .Values.persistence.downloads.existingClaim }}{{ .Values.persistence.downloads.existingClaim }}{{ else }}{{ include "pinepods.fullname" . }}-downloads{{ end }}
        - name: backups
          persistentVolumeClaim:
            claimName: {{ if .Values.persistence.backups.existingClaim }}{{ .Values.persistence.backups.existingClaim }}{{ else }}{{ include "pinepods.fullname" . }}-backups{{ end }}
        {{- end }}
