#!/usr/bin/env bash
# Auto-backup for canteen-asset-tracker database
# Runs before every server start and on a cron schedule

set -euo pipefail

DB_DIR="/home/oplabs/projects/canteen-asset-tracker"
BACKUP_DIR="/home/oplabs/backups/canteen-db"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

mkdir -p "$BACKUP_DIR"

for db in assets.db; do
    if [ -f "${DB_DIR}/${db}" ]; then
        cp "${DB_DIR}/${db}" "${BACKUP_DIR}/${db}-${TIMESTAMP}"
        # Keep only last 30 backups
        ls -t "${BACKUP_DIR}/${db}-"* 2>/dev/null | tail -n +31 | xargs rm -f 2>/dev/null || true
        echo "✅ Backed up ${db} -> ${BACKUP_DIR}/${db}-${TIMESTAMP}"
    else
        echo "⚠️ ${db} not found, skipping"
    fi
done
