#!/bin/bash
# TimeMaster Backup Script
# Sichert PostgreSQL-Datenbank und pip-Paketliste
set -euo pipefail

BACKUP_DIR="/tank/backup"
DB_NAME="timemaster_db"
DB_USER="timemaster"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=30

echo "[$(date)] Starting TimeMaster backup..."

mkdir -p "$BACKUP_DIR"

# PostgreSQL dump (custom format, komprimiert) — peer auth erfordert su
su -c "pg_dump -Fc $DB_NAME" postgres > "$BACKUP_DIR/db_$TIMESTAMP.dump"
SIZE=$(du -sh "$BACKUP_DIR/db_$TIMESTAMP.dump" | cut -f1)
echo "[$(date)] DB backup: db_$TIMESTAMP.dump ($SIZE)"

# pip freeze für venv (für venv-Wiederherstellung nach Python-Upgrade)
/opt/timemaster/backend/venv/bin/pip freeze > "$BACKUP_DIR/requirements_frozen_$TIMESTAMP.txt"
echo "[$(date)] pip freeze: requirements_frozen_$TIMESTAMP.txt"

# Alembic-Version sichern
su -c "psql $DB_NAME -t -c 'SELECT version_num FROM alembic_version;'" postgres 2>/dev/null \
  > "$BACKUP_DIR/alembic_version_$TIMESTAMP.txt" || true

# PostgreSQL-Version sichern (wichtig für pg_upgrade-Erkennung)
su -c "psql -t -c 'SELECT version();'" postgres 2>/dev/null \
  | head -1 | xargs > "$BACKUP_DIR/pg_version_$TIMESTAMP.txt" || true

# Alte Backups löschen (älter als RETENTION_DAYS)
find "$BACKUP_DIR" -name "db_*.dump"                    -mtime +$RETENTION_DAYS -delete
find "$BACKUP_DIR" -name "requirements_frozen_*.txt"    -mtime +$RETENTION_DAYS -delete
find "$BACKUP_DIR" -name "alembic_version_*.txt"        -mtime +$RETENTION_DAYS -delete
find "$BACKUP_DIR" -name "pg_version_*.txt"             -mtime +$RETENTION_DAYS -delete

echo "[$(date)] Backup complete. Current backups:"
ls -lh "$BACKUP_DIR"
echo "[$(date)] Total size: $(du -sh "$BACKUP_DIR" | cut -f1)"
