#!/bin/bash
# backup-pg.sh — Daglig PostgreSQL-dump med rotasjon.
#
# Kjøres via cron (03:00 UTC). Dumper synops-databasen med pg_dump -Fc
# (custom format, komprimert). Beholder 30 dager, sletter eldre.
#
# Ref: docs/setup/produksjon.md § 11.1, docs/infra/backup.md

set -euo pipefail

BACKUP_DIR="/srv/synops/backup/pg"
CONTAINER="sidelinja-postgres-1"
DB_USER="sidelinja"
DB_NAME="sidelinja"
RETAIN_DAYS=30
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
DUMP_FILE="${BACKUP_DIR}/${DB_NAME}_${TIMESTAMP}.dump"
LOG_FILE="/srv/synops/logs/backup-pg.log"

log() {
    echo "$(date -Iseconds) $1" | tee -a "$LOG_FILE"
}

# Sjekk at backup-katalog finnes
mkdir -p "$BACKUP_DIR"

# Sjekk at PG-containeren kjører
if ! docker inspect "$CONTAINER" --format '{{.State.Running}}' 2>/dev/null | grep -q true; then
    log "FEIL: PostgreSQL-container $CONTAINER kjører ikke"
    exit 1
fi

# Kjør pg_dump (konsistent snapshot, ingen nedetid)
log "Starter PG-dump → $DUMP_FILE"
if docker exec "$CONTAINER" pg_dump -U "$DB_USER" -Fc "$DB_NAME" > "$DUMP_FILE" 2>>"$LOG_FILE"; then
    # Verifiser at filen ikke er tom
    FILESIZE=$(stat -c%s "$DUMP_FILE" 2>/dev/null || echo 0)
    if [ "$FILESIZE" -lt 100 ]; then
        log "FEIL: Dump-filen er for liten (${FILESIZE} bytes), noe gikk galt"
        rm -f "$DUMP_FILE"
        exit 1
    fi
    log "PG-dump ferdig: ${DUMP_FILE} ($(numfmt --to=iec "$FILESIZE"))"
else
    log "FEIL: pg_dump feilet"
    rm -f "$DUMP_FILE"
    exit 1
fi

# Rotasjon: slett dumper eldre enn $RETAIN_DAYS dager
DELETED=$(find "$BACKUP_DIR" -name "*.dump" -mtime +${RETAIN_DAYS} -print -delete | wc -l)
if [ "$DELETED" -gt 0 ]; then
    log "Rotasjon: slettet $DELETED dump(er) eldre enn $RETAIN_DAYS dager"
fi

log "Backup fullført OK"
