#!/usr/bin/env bash
# Daily backup: database dump + uploaded files (receipts, notes). Keeps the last 14 days.
# cPanel cron:  30 2 * * *  /bin/bash /home/USER/drideas/scripts/backup.sh
# Credentials are read from config/config.php; the dump is never placed inside public/.
set -euo pipefail

APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
BACKUP_DIR="${BACKUP_DIR:-$HOME/drideas-backups}"
STAMP="$(date +%Y-%m-%d_%H%M)"
KEEP_DAYS=14

read_cfg() { php -r '$c = require $argv[1]; echo $c["db"][$argv[2]];' "$APP_DIR/config/config.php" "$1"; }
DB_HOST="$(read_cfg host)"; DB_NAME="$(read_cfg name)"; DB_USER="$(read_cfg user)"; DB_PASS="$(read_cfg pass)"

umask 077
mkdir -p "$BACKUP_DIR"

# Password via a temp option file so it never appears in the process list.
OPT="$(mktemp)"; trap 'rm -f "$OPT"' EXIT
printf '[client]\nhost=%s\nuser=%s\npassword=%s\n' "$DB_HOST" "$DB_USER" "$DB_PASS" > "$OPT"

mysqldump --defaults-extra-file="$OPT" --single-transaction --routines "$DB_NAME" | gzip > "$BACKUP_DIR/db_$STAMP.sql.gz"
tar -czf "$BACKUP_DIR/files_$STAMP.tar.gz" --exclude='storage/.htaccess' -C "$APP_DIR" storage

find "$BACKUP_DIR" -type f \( -name 'db_*.sql.gz' -o -name 'files_*.tar.gz' \) -mtime +"$KEEP_DAYS" -delete
echo "Backup complete: $BACKUP_DIR ($STAMP)"
echo "REMINDER: copy these off the server regularly (Google Drive / another host)."
