apiVersion: batch/v1
kind: Job
metadata:
  name: pg-cleanup
spec:
  ttlSecondsAfterFinished: 300
  template:
    spec:
      containers:
      - name: pg-cleanup
        image: 485790562880.dkr.ecr.us-east-2.amazonaws.com/akamas/bitnami/postgresql:16.6.0-debian-12-r2
        command:
        - /bin/bash
        - -c
        - |
          # Ensure the database is not running before cleaning up
          if pg_isready -h database -p 5432 2>/dev/null; then
            echo "ERROR: database is still running. Scale it down first."
            exit 1
          fi
          # Ensure the datadir exists and is not empty (guard against repeated runs)
          if [ ! -d "/data/data" ] || [ -z "$(ls -A /data/data)" ]; then
            echo "ERROR: datadir /data/data is missing or empty. Already cleaned up?"
            exit 1
          fi
          echo "Removing datadir for PG version: $(cat /data/data/PG_VERSION)"
          OUT="/backup/dump$(date +%s)"
          echo "Backing up datadir to $OUT"
          cp -a "/data/data" "$OUT"
          rm -rf /data/data
          echo " *** Cleanup completed ***"
        volumeMounts:
        - name: datadir
          mountPath: /data
        - name: backup
          mountPath: /backup

      volumes:
      - name: datadir
        persistentVolumeClaim:
          claimName: data-database-0
      - name: backup
        persistentVolumeClaim:
          claimName: pg-dump
      restartPolicy: Never
  backoffLimit: 2
