#!/usr/bin/env bash
# Backup of the central database and EVERY business database, plus both applications' .env and the registry.
#   bash scripts/backup-all.sh            (run from the kaabe folder; used by cron nightly)
# Credentials are read by the platform itself and written to a 0600 temporary option file, never on the command line.
set -euo pipefail
umask 077   # dumps and .env copies contain secrets
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; PHP="${KAABE_PHP_BINARY:-php}"
DEST="${KAABE_BACKUP_DIR:-$HOME/kaabe-backups}/$(date -u +%Y%m%dT%H%M%SZ)"; mkdir -p "$DEST"; chmod 700 "$(dirname "$DEST")" "$DEST"
cd "$ROOT/platform"
"$PHP" artisan kaabe:backup "$DEST"
tar -czf "$DEST/config.tar.gz" -C "$ROOT" platform/.env pos/kaabe/.env 2>/dev/null || true
# the registry path comes from the environment or, under cron, from platform/.env
REG="${KAABE_REGISTRY_PATH:-$(grep -E '^KAABE_REGISTRY_PATH=' "$ROOT/platform/.env" 2>/dev/null | head -1 | cut -d= -f2- | sed -e 's/[[:space:]]*#.*$//' -e 's/^"//' -e 's/"$//')}"
if [ -n "$REG" ] && [ -f "$REG" ]; then cp "$REG" "$DEST/"; else echo "WARNING: tenant registry not found (KAABE_REGISTRY_PATH) – not included"; fi
( cd "$DEST" && sha256sum * > SHA256SUMS )
# retention: keep the newest 7 daily backups
ls -1dt "$(dirname "$DEST")"/*/ 2>/dev/null | tail -n +8 | xargs -r rm -rf
echo "Backup complete: $DEST"
echo "Copy it OFF the server (see BACKUP-RESTORE.md)."
