#!/bin/bash
# DocFast SQLite Backup Script
# Runs every 6 hours via cron. Keeps 7 daily + 4 weekly backups.

set -euo pipefail

BACKUP_DIR="/opt/docfast-backups"
DB_PATH="/var/lib/docker/volumes/docfast_docfast-data/_data/docfast.db"
DATE=$(date +%Y-%m-%d_%H%M)
DAY_OF_WEEK=$(date +%u)  # 1=Monday, 7=Sunday

mkdir -p "$BACKUP_DIR"

# Check if database exists
if [[ ! -f "$DB_PATH" ]]; then
    echo "ERROR: Database not found at $DB_PATH" >&2
    exit 1
fi

# Safe hot backup using sqlite3 .backup
DAILY_FILE="$BACKUP_DIR/docfast-daily-${DATE}.db"
sqlite3 "$DB_PATH" ".backup '$DAILY_FILE'"

# Verify backup is valid
if ! sqlite3 "$DAILY_FILE" "PRAGMA integrity_check;" | grep -q "^ok$"; then
    echo "ERROR: Backup integrity check failed!" >&2
    rm -f "$DAILY_FILE"
    exit 1
fi

echo "Created backup: $DAILY_FILE ($(stat -c%s "$DAILY_FILE") bytes)"

# On Sundays, also keep a weekly copy
if [ "$DAY_OF_WEEK" -eq 7 ]; then
    WEEKLY_FILE="$BACKUP_DIR/docfast-weekly-$(date +%Y-%m-%d).db"
    cp "$DAILY_FILE" "$WEEKLY_FILE"
    echo "Created weekly backup: $WEEKLY_FILE"
fi

# Rotate: keep last 7 daily backups (28 files at 6h intervals = ~7 days)
find "$BACKUP_DIR" -name "docfast-daily-*.db" -type f | sort -r | tail -n +29 | xargs -r rm -f

# Rotate: keep last 4 weekly backups
find "$BACKUP_DIR" -name "docfast-weekly-*.db" -type f | sort -r | tail -n +5 | xargs -r rm -f || true

# Show current backup status
DAILY_COUNT=$(find "$BACKUP_DIR" -name "docfast-daily-*.db" -type f | wc -l)
WEEKLY_COUNT=$(find "$BACKUP_DIR" -name "docfast-weekly-*.db" -type f | wc -l)
echo "Backup rotation complete. Daily: $DAILY_COUNT, Weekly: $WEEKLY_COUNT"