apiVersion: batch/v1
kind: Job
metadata:
  name: pg-dump
spec:
  ttlSecondsAfterFinished: 300
  template:
    spec:
      initContainers:
      - name: wait-for-database
        image: 485790562880.dkr.ecr.us-east-2.amazonaws.com/akamas/bitnami/postgresql:16.6.0-debian-12-r2
        command:
        - /bin/bash
        - -c
        - |
          until pg_isready -h database -p 5432; do
            echo "Waiting for database to be ready...";
            sleep 2
          done
        env:
        - name: PGHOST
          value: database
        - name: PGUSER
          value: postgres
        - name: PGPASSWORD
          valueFrom:
            secretKeyRef:
              name: database
              key: postgres-password

      containers:
      - name: pg-dump
        image: 485790562880.dkr.ecr.us-east-2.amazonaws.com/akamas/bitnami/postgresql:16.6.0-debian-12-r2
        command:
        - /bin/bash
        - -c
        - |
          mkdir -p /backup/dumps
          pg_dumpall --clean --if-exists -f /backup/dumps/dump.sql
          echo "Backup created at $(date)"
          echo Dumped $(wc -l /backup/dumps/dump.sql) lines
          echo " *** Backup completed ***"
        env:
        - name: PGHOST
          value: database
        - name: PGUSER
          value: postgres
        - name: PGPASSWORD
          valueFrom:
            secretKeyRef:
              name: database
              key: postgres-password
        volumeMounts:
        - name: backup
          mountPath: /backup
      volumes:
      - name: backup
        persistentVolumeClaim:
          claimName: pg-dump
      restartPolicy: Never
  backoffLimit: 2

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pg-dump
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      # Increase this value if your database is larger than 10Gi
      storage: 10Gi
