#!/usr/bin/env bash
#
# Daily production backup — database dump + storage/app/public (organizer
# uploads: banners, thumbnails, gallery, signature artist photos, etc.).
# See documentation/backup-and-recovery.md for the restore procedure and why
# a separate, secure backup of .env (APP_KEY especially) is required too —
# this script intentionally does NOT back up .env itself (it should never
# sit unencrypted next to a DB dump).
#
# Cron (production VPS only — not needed/used in local dev):
#   0 2 * * * KOLABORA_BACKUP_DIR=/var/backups/kolabora /path/to/apps/backend/scripts/backup-database.sh >> /var/log/kolabora-backup.log 2>&1
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/../.env"
BACKUP_DIR="${KOLABORA_BACKUP_DIR:-/var/backups/kolabora}"
RETENTION_DAYS="${KOLABORA_BACKUP_RETENTION_DAYS:-14}"

if [ ! -f "$ENV_FILE" ]; then
  echo "No .env found at $ENV_FILE — aborting." >&2
  exit 1
fi

DB_HOST=$(grep -E '^DB_HOST=' "$ENV_FILE" | cut -d '=' -f2-)
DB_PORT=$(grep -E '^DB_PORT=' "$ENV_FILE" | cut -d '=' -f2-)
DB_DATABASE=$(grep -E '^DB_DATABASE=' "$ENV_FILE" | cut -d '=' -f2-)
DB_USERNAME=$(grep -E '^DB_USERNAME=' "$ENV_FILE" | cut -d '=' -f2-)
DB_PASSWORD=$(grep -E '^DB_PASSWORD=' "$ENV_FILE" | cut -d '=' -f2-)

mkdir -p "$BACKUP_DIR"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)

# --- Database ---
DB_OUT="$BACKUP_DIR/kolabora-db-$TIMESTAMP.sql.gz"
MYSQL_PWD="$DB_PASSWORD" mysqldump \
  --host="$DB_HOST" --port="${DB_PORT:-3306}" --user="$DB_USERNAME" \
  --single-transaction --quick --routines --triggers \
  "$DB_DATABASE" | gzip > "$DB_OUT"
echo "Database backup written: $DB_OUT"
find "$BACKUP_DIR" -name 'kolabora-db-*.sql.gz' -mtime +"$RETENTION_DAYS" -delete

# --- Storage (organizer-uploaded files) ---
STORAGE_DIR="$SCRIPT_DIR/../storage/app/public"
if [ -d "$STORAGE_DIR" ]; then
  STORAGE_OUT="$BACKUP_DIR/kolabora-storage-$TIMESTAMP.tar.gz"
  tar -czf "$STORAGE_OUT" -C "$STORAGE_DIR" .
  echo "Storage backup written: $STORAGE_OUT"
  find "$BACKUP_DIR" -name 'kolabora-storage-*.tar.gz' -mtime +"$RETENTION_DAYS" -delete
fi

echo "Done. Reminder: $BACKUP_DIR should be synced off this server (S3, another host, etc.) — a backup that only lives on the same VPS doesn't survive losing the VPS."
