apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-init
  namespace: atproto
data:
  init.sql: |
    CREATE DATABASE plc;
    GRANT ALL PRIVILEGES ON DATABASE plc TO postgres;
    CREATE DATABASE bgs;
    CREATE DATABASE carstore;
    GRANT ALL PRIVILEGES ON DATABASE bgs TO postgres;
    GRANT ALL PRIVILEGES ON DATABASE carstore TO postgres;
    CREATE DATABASE bsky;
    GRANT ALL PRIVILEGES ON DATABASE bsky TO postgres;
    CREATE DATABASE ozone;
    GRANT ALL PRIVILEGES ON DATABASE ozone TO postgres;
    CREATE DATABASE pds;
    GRANT ALL PRIVILEGES ON DATABASE pds TO postgres;
    CREATE DATABASE bsync;
    GRANT ALL PRIVILEGES ON DATABASE bsync TO postgres;
---
apiVersion: v1
kind: Service
metadata:
  name: database
  namespace: atproto
spec:
  selector:
    app: postgres
  ports:
    - port: 5432
      targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: atproto
spec:
  serviceName: database
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:16-alpine
          env:
            - name: POSTGRES_USER
              value: postgres
            - name: POSTGRES_PASSWORD
              value: postgres
            - name: POSTGRES_DB
              value: healthcheck
          ports:
            - containerPort: 5432
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
            - name: init
              mountPath: /docker-entrypoint-initdb.d
          livenessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres", "-d", "healthcheck"]
            initialDelaySeconds: 10
            periodSeconds: 5
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "postgres", "-d", "healthcheck"]
            initialDelaySeconds: 5
            periodSeconds: 5
      volumes:
        - name: init
          configMap:
            name: postgres-init
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 20Gi
