#!/bin/bash
# Periodic PostgreSQL backup for PedsHub
# Keeps the last 14 daily backups, rotating old ones out.

BACKUP_DIR="/home/danvics/docker/quiz/backups"
COMPOSE_DIR="/home/danvics/docker/quiz"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
FILENAME="pedquiz_${TIMESTAMP}.sql.gz"

mkdir -p "$BACKUP_DIR"

# Dump via the running postgres container
docker compose -f "$COMPOSE_DIR/docker-compose.yml" exec -T postgres \
  pg_dump -U pedquiz pedquiz | gzip > "$BACKUP_DIR/$FILENAME"

if [ $? -eq 0 ] && [ -s "$BACKUP_DIR/$FILENAME" ]; then
  echo "[$(date)] Backup OK: $FILENAME ($(du -h "$BACKUP_DIR/$FILENAME" | cut -f1))"
else
  echo "[$(date)] Backup FAILED" >&2
  rm -f "$BACKUP_DIR/$FILENAME"
  exit 1
fi

# Rotate: keep last 14 backups
ls -1t "$BACKUP_DIR"/pedquiz_*.sql.gz 2>/dev/null | tail -n +15 | xargs -r rm --
