{{- if .Values.postgresql.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ include "hindsight.fullname" . }}-postgresql
  labels:
    {{- include "hindsight.labels" . | nindent 4 }}
    app.kubernetes.io/component: postgresql
spec:
  serviceName: {{ include "hindsight.fullname" . }}-postgresql
  replicas: 1
  selector:
    matchLabels:
      {{- include "hindsight.selectorLabels" . | nindent 6 }}
      app.kubernetes.io/component: postgresql
  template:
    metadata:
      labels:
        {{- include "hindsight.selectorLabels" . | nindent 8 }}
        app.kubernetes.io/component: postgresql
    spec:
      containers:
      - name: postgresql
        image: "{{ .Values.postgresql.image.repository }}:{{ .Values.postgresql.image.tag }}"
        imagePullPolicy: {{ .Values.postgresql.image.pullPolicy }}
        ports:
        - name: postgresql
          containerPort: 5432
          protocol: TCP
        env:
        - name: POSTGRES_USER
          value: {{ .Values.postgresql.auth.username | quote }}
        - name: POSTGRES_PASSWORD
          value: {{ .Values.postgresql.auth.password | quote }}
        - name: POSTGRES_DB
          value: {{ .Values.postgresql.auth.database | quote }}
        - name: PGDATA
          value: /var/lib/postgresql/data/pgdata
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -U
            - {{ .Values.postgresql.auth.username }}
            - -d
            - {{ .Values.postgresql.auth.database }}
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 3
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -U
            - {{ .Values.postgresql.auth.username }}
            - -d
            - {{ .Values.postgresql.auth.database }}
          initialDelaySeconds: 5
          periodSeconds: 5
          timeoutSeconds: 3
          failureThreshold: 3
        resources:
          {{- toYaml .Values.postgresql.resources | nindent 10 }}
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
  {{- if .Values.postgresql.persistence.enabled }}
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      {{- if .Values.postgresql.persistence.storageClass }}
      storageClassName: {{ .Values.postgresql.persistence.storageClass | quote }}
      {{- end }}
      resources:
        requests:
          storage: {{ .Values.postgresql.persistence.size }}
  {{- else }}
      volumes:
      - name: data
        emptyDir: {}
  {{- end }}
{{- end }}
