#!/bin/bash
# ═══════════════════════════════════════════════════════════════
#  Venture Fund CRM — Database Backup Script
# ═══════════════════════════════════════════════════════════════
#
#  Usage:
#    ./scripts/backup.sh                    # Backup to ./backups/
#    ./scripts/backup.sh /path/to/backups   # Backup to custom dir
#
#  Automate with cron:
#    crontab -e
#    0 2 * * * /path/to/venture-crm/scripts/backup.sh >> /var/log/crm-backup.log 2>&1
#
# ═══════════════════════════════════════════════════════════════

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
DB_PATH="$PROJECT_DIR/data/crm.db"
BACKUP_DIR="${1:-$PROJECT_DIR/backups}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/crm_backup_$TIMESTAMP.db"

# Create backup directory
mkdir -p "$BACKUP_DIR"

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

# Use SQLite's backup command for a safe, consistent backup
# This works even if the server is running
sqlite3 "$DB_PATH" ".backup '$BACKUP_FILE'"

# Get file size
SIZE=$(du -h "$BACKUP_FILE" | cut -f1)

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backup created: $BACKUP_FILE ($SIZE)"

# Clean up old backups (keep last 30)
BACKUP_COUNT=$(ls -1 "$BACKUP_DIR"/crm_backup_*.db 2>/dev/null | wc -l)
if [ "$BACKUP_COUNT" -gt 30 ]; then
    REMOVE_COUNT=$((BACKUP_COUNT - 30))
    ls -1t "$BACKUP_DIR"/crm_backup_*.db | tail -n "$REMOVE_COUNT" | xargs rm -f
    echo "  Cleaned up $REMOVE_COUNT old backup(s). Keeping last 30."
fi
