#!/usr/bin/env bash
#
# backup.sh — Backs up the SQLite database using SQLite's online backup API.
#
# This is safe to run while the Flask app is live because it uses
# SQLite's .backup command, which handles file locking internally.
#
# Usage:
#   ./scripts/backup.sh
#
# Cron (daily at 2 AM):
#   0 2 * * * /path/to/yourbookshelf/scripts/backup.sh >> /path/to/backups/cron.log 2>&1
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

DB_PATH="${SQLALCHEMY_DATABASE_URI:-}"
# If env var is set, extract the file path from the URI (strip sqlite:/// prefix)
if [[ -n "$DB_PATH" ]]; then
    DB_FILE="${DB_PATH#sqlite:///}"
else
    # Default: instance/books-collection.db
    DB_FILE="$PROJECT_ROOT/instance/books-collection.db"
fi

BACKUP_DIR="${BACKUP_DIR:-$PROJECT_ROOT/backups}"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP_FILE="$BACKUP_DIR/books-backup_${TIMESTAMP}.db"

# Retention: keep the last N backups (default 7)
RETENTION="${BACKUP_RETENTION:-7}"

if [[ ! -f "$DB_FILE" ]]; then
    echo "ERROR: Database file not found at $DB_FILE"
    exit 1
fi

mkdir -p "$BACKUP_DIR"

echo "Backing up $DB_FILE -> $BACKUP_FILE"
sqlite3 "$DB_FILE" ".backup '$BACKUP_FILE'"

if [[ $? -eq 0 ]]; then
    echo "Backup completed successfully."
else
    echo "Backup FAILED."
    exit 1
fi

# Prune old backups
echo "Pruning backups older than retention count of $RETENTION"
ls -t "$BACKUP_DIR"/books-backup_*.db 2>/dev/null | tail -n +$((RETENTION + 1)) | while read -r old_file; do
    echo "Removing old backup: $old_file"
    rm -f "$old_file"
done

echo "Done."
