#!/usr/bin/env bash
# MyBurn backup script — Operacao BUNKER
# Usage: ./scripts/backup.sh [data_dir] [backup_dir]
# Cron: 0 */6 * * * /home/gekko/projects/ccusage-dashboard/scripts/backup.sh

set -euo pipefail

DATA_DIR="${1:-${MYBURN_DATA_DIR:-$HOME/.myburn/data}}"
BACKUP_DIR="${2:-$HOME/.myburn/backups}"
RETENTION_DAYS=7
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

mkdir -p "$BACKUP_DIR"

# Use Python's sqlite3 .backup() API — safe during WAL writes
backup_db() {
    local src="$1"
    local dst="$2"
    local name="$3"
    python3 -c "
import sqlite3, sys
src = sqlite3.connect('$src')
dst = sqlite3.connect('$dst')
src.backup(dst)
dst.close()
src.close()
" && echo "[OK] $name → $dst ($(du -h "$dst" | cut -f1))" \
  || echo "[FAIL] $name backup failed"
}

# Backup usage.db (main database)
if [ -f "$DATA_DIR/usage.db" ]; then
    backup_db "$DATA_DIR/usage.db" "$BACKUP_DIR/usage_$TIMESTAMP.db" "usage.db"
else
    echo "[SKIP] usage.db not found at $DATA_DIR"
fi

# Backup cloud.db (if exists — only on VPS)
if [ -f "$DATA_DIR/cloud.db" ]; then
    backup_db "$DATA_DIR/cloud.db" "$BACKUP_DIR/cloud_$TIMESTAMP.db" "cloud.db"
fi

# Also check the alternative cloud.db location
CLOUD_ALT="$HOME/.myburn/data/cloud.db"
if [ -f "$CLOUD_ALT" ] && [ "$CLOUD_ALT" != "$DATA_DIR/cloud.db" ]; then
    backup_db "$CLOUD_ALT" "$BACKUP_DIR/cloud_$TIMESTAMP.db" "cloud.db (alt)"
fi

# Cleanup old backups (retention policy)
find "$BACKUP_DIR" -name "*.db" -mtime +$RETENTION_DAYS -delete 2>/dev/null
REMAINING=$(find "$BACKUP_DIR" -name "*.db" | wc -l)
echo "[CLEANUP] Removed backups older than ${RETENTION_DAYS}d. $REMAINING backups retained."
