#!/bin/bash
# Hourly database backup script
# Keeps last 720 backups (30 days of hourly backups)

BACKUP_DIR="/mnt/video/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
MAX_BACKUPS=720

# Backup prod
if [ -f /mnt/video/videobot_prod.db ]; then
    sqlite3 /mnt/video/videobot_prod.db ".backup '${BACKUP_DIR}/videobot_prod_${TIMESTAMP}.db'"
fi

# Backup dev
if [ -f /mnt/video/videobot_dev.db ]; then
    sqlite3 /mnt/video/videobot_dev.db ".backup '${BACKUP_DIR}/videobot_dev_${TIMESTAMP}.db'"
fi

# Cleanup old backups — keep only last MAX_BACKUPS per database
for prefix in videobot_prod videobot_dev; do
    count=$(ls -1t "${BACKUP_DIR}/${prefix}_"*.db 2>/dev/null | wc -l)
    if [ "$count" -gt "$MAX_BACKUPS" ]; then
        ls -1t "${BACKUP_DIR}/${prefix}_"*.db | tail -n +$((MAX_BACKUPS + 1)) | xargs rm -f
    fi
done
