{{- if .Values.postgresql.enabled }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: {{ include "rise.fullname" . }}-postgresql
  labels:
    {{- include "rise.labels" . | nindent 4 }}
    app.kubernetes.io/component: postgresql
spec:
  serviceName: {{ include "rise.fullname" . }}-postgresql
  replicas: 1
  selector:
    matchLabels:
      {{- include "rise.selectorLabels" . | nindent 6 }}
      app.kubernetes.io/component: postgresql
  template:
    metadata:
      labels:
        {{- include "rise.selectorLabels" . | nindent 8 }}
        app.kubernetes.io/component: postgresql
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 999  # postgres user in official image
        fsGroup: 999
      containers:
      - name: postgresql
        image: "{{ .Values.postgresql.image.repository }}:{{ .Values.postgresql.image.tag }}"
        imagePullPolicy: {{ .Values.postgresql.image.pullPolicy }}
        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
        ports:
        - name: postgresql
          containerPort: 5432
          protocol: TCP
        livenessProbe:
          exec:
            command:
            - /bin/sh
            - -c
            - pg_isready -U {{ .Values.postgresql.auth.username }}
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 6
        readinessProbe:
          exec:
            command:
            - /bin/sh
            - -c
            - pg_isready -U {{ .Values.postgresql.auth.username }}
          initialDelaySeconds: 5
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 6
        {{- if .Values.postgresql.persistence.enabled }}
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
        {{- end }}
        resources:
          {{- toYaml .Values.postgresql.resources | nindent 12 }}
  {{- if .Values.postgresql.persistence.enabled }}
  volumeClaimTemplates:
  - metadata:
      name: data
      labels:
        {{- include "rise.selectorLabels" . | nindent 8 }}
        app.kubernetes.io/component: postgresql
    spec:
      accessModes:
        - ReadWriteOnce
      {{- if .Values.postgresql.persistence.storageClass }}
      {{- if (eq "-" .Values.postgresql.persistence.storageClass) }}
      storageClassName: ""
      {{- else }}
      storageClassName: {{ .Values.postgresql.persistence.storageClass | quote }}
      {{- end }}
      {{- end }}
      resources:
        requests:
          storage: {{ .Values.postgresql.persistence.size | quote }}
  {{- end }}
{{- end }}
