{{- if .Values.postgres.enabled }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ include "eddi.fullname" . }}-postgres
  labels:
    {{- include "eddi.labels" . | nindent 4 }}
    app.kubernetes.io/component: database
type: Opaque
stringData:
  POSTGRES_DB: {{ .Values.postgres.database | quote }}
  POSTGRES_USER: {{ .Values.postgres.username | quote }}
  POSTGRES_PASSWORD: {{ .Values.postgres.password | quote }}
  QUARKUS_DATASOURCE_USERNAME: {{ .Values.postgres.username | quote }}
  QUARKUS_DATASOURCE_PASSWORD: {{ .Values.postgres.password | quote }}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ include "eddi.fullname" . }}-postgres
  labels:
    {{- include "eddi.labels" . | nindent 4 }}
    app.kubernetes.io/component: database
spec:
  serviceName: {{ include "eddi.fullname" . }}-postgres
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "eddi.fullname" . }}-postgres
      app.kubernetes.io/component: database
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "eddi.fullname" . }}-postgres
        app.kubernetes.io/component: database
        app.kubernetes.io/part-of: eddi
    spec:
      securityContext:
        fsGroup: 999
      containers:
        - name: postgres
          image: "{{ .Values.postgres.image.repository }}:{{ .Values.postgres.image.tag }}"
          ports:
            - containerPort: 5432
              name: postgres
          envFrom:
            - secretRef:
                name: {{ include "eddi.fullname" . }}-postgres
          env:
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          volumeMounts:
            - name: pgdata
              mountPath: /var/lib/postgresql/data
          resources:
            {{- toYaml .Values.postgres.resources | nindent 12 }}
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", {{ .Values.postgres.username | quote }}, "-d", {{ .Values.postgres.database | quote }}]
            initialDelaySeconds: 5
            periodSeconds: 10
  volumeClaimTemplates:
    - metadata:
        name: pgdata
      spec:
        accessModes: ["ReadWriteOnce"]
        {{- if .Values.postgres.storage.storageClassName }}
        storageClassName: {{ .Values.postgres.storage.storageClassName | quote }}
        {{- end }}
        resources:
          requests:
            storage: {{ .Values.postgres.storage.size }}
---
apiVersion: v1
kind: Service
metadata:
  name: {{ include "eddi.fullname" . }}-postgres
  labels:
    {{- include "eddi.labels" . | nindent 4 }}
    app.kubernetes.io/component: database
spec:
  type: ClusterIP
  clusterIP: None
  selector:
    app.kubernetes.io/name: {{ include "eddi.fullname" . }}-postgres
    app.kubernetes.io/component: database
  ports:
    - name: postgres
      port: 5432
      targetPort: postgres
{{- end }}
