# PostgreSQL 16 — shared RDBMS for Authentik + OCIS (mirrors the dev stack).
# Single-node StatefulSet on k3s local-path storage. Logical dumps for backup
# are added by a pg_dump CronJob (Restic captures the dump dir on the host).
apiVersion: v1
kind: Service
metadata:
  name: postgres
  namespace: dezky-data
spec:
  clusterIP: None          # headless: stable DNS postgres.dezky-data:5432
  selector:
    app: postgres
  ports:
    - name: postgres
      port: 5432
      targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: dezky-data
spec:
  serviceName: postgres
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      # No fsGroup needed: the postgres image entrypoint runs as root and
      # chowns PGDATA to the postgres user before stepping down.
      containers:
        - name: postgres
          image: postgres:16-alpine
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_USER
              value: postgres
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata   # subdir avoids lost+found clash
          envFrom:
            - secretRef:
                name: postgres-secret    # POSTGRES_PASSWORD, AUTHENTIK_DB_PASSWORD, OCIS_DB_PASSWORD
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
            - name: init
              mountPath: /docker-entrypoint-initdb.d
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              memory: 1Gi
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres"]
            initialDelaySeconds: 10
            periodSeconds: 10
          livenessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres"]
            initialDelaySeconds: 30
            periodSeconds: 20
      volumes:
        - name: init
          configMap:
            name: postgres-init
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: longhorn
        resources:
          requests:
            storage: 10Gi
