{{- if .Values.postgresql.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ include "proxmox-api-simulator.postgresqlHost" . }}
  labels:
    {{- include "proxmox-api-simulator.labels" . | nindent 4 }}
    app.kubernetes.io/component: postgresql
spec:
  serviceName: {{ include "proxmox-api-simulator.postgresqlHost" . }}
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "proxmox-api-simulator.name" . }}-postgresql
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "proxmox-api-simulator.name" . }}-postgresql
        app.kubernetes.io/instance: {{ .Release.Name }}
        app.kubernetes.io/component: postgresql
    spec:
      containers:
        - name: postgresql
          image: {{ printf "%s:%s" .Values.postgresql.image.repository .Values.postgresql.image.tag | quote }}
          imagePullPolicy: {{ .Values.postgresql.image.pullPolicy }}
          ports:
            - name: postgresql
              containerPort: 5432
          env:
            - name: POSTGRES_DB
              value: {{ .Values.postgresql.auth.database | quote }}
            - name: POSTGRES_USER
              value: {{ .Values.postgresql.auth.username | quote }}
            - name: POSTGRES_PASSWORD
              value: {{ .Values.postgresql.auth.password | quote }}
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          livenessProbe:
            exec:
              command: ["pg_isready", "-U", {{ .Values.postgresql.auth.username | quote }}]
            initialDelaySeconds: 20
            periodSeconds: 10
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", {{ .Values.postgresql.auth.username | quote }}]
            initialDelaySeconds: 5
            periodSeconds: 5
          resources:
            {{- toYaml .Values.postgresql.resources | nindent 12 }}
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  {{- if .Values.postgresql.persistence.enabled }}
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        {{- with .Values.postgresql.persistence.storageClass }}
        storageClassName: {{ . | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.postgresql.persistence.size }}
  {{- else }}
      volumes:
        - name: data
          emptyDir: {}
  {{- end }}
{{- end }}
