#!/bin/bash
# Firefrost Arbiter - Automated Backup Script
# Location: /home/architect/arbiter/backup.sh
# Scheduled: Daily at 4:00 AM CST via crontab

APP_DIR="/home/architect/arbiter"
BACKUP_DIR="/home/architect/backups/arbiter"
DATE=$(date +%Y%m%d_%H%M%S)
LOG_FILE="$BACKUP_DIR/backup_log.txt"

# Ensure the backup directory exists
mkdir -p "$BACKUP_DIR"
echo "--- Backup Started: $DATE ---" >> "$LOG_FILE"

# Safely backup databases using SQLite native backup
if ! sqlite3 "$APP_DIR/linking.db" ".backup '$BACKUP_DIR/linking_$DATE.db'"; then
    echo "ERROR: Failed to backup linking.db" >> "$LOG_FILE"
    exit 1
fi

if ! sqlite3 "$APP_DIR/sessions.db" ".backup '$BACKUP_DIR/sessions_$DATE.db'"; then
    echo "ERROR: Failed to backup sessions.db" >> "$LOG_FILE"
    exit 1
fi

# Copy config and environment files
cp "$APP_DIR/.env" "$BACKUP_DIR/env_$DATE.bak"
cp "$APP_DIR/config/roles.json" "$BACKUP_DIR/roles_$DATE.json"

# Delete backups older than 7 days to save disk space
find "$BACKUP_DIR" -type f -mtime +7 -delete

echo "Backup completed successfully." >> "$LOG_FILE"
