#!/usr/bin/env bash
# Nightly backup: database + private files (photos, signatures, documents). Usage: bash deploy/backup.sh /var/www/dms [/var/backups/dms]
# Copy the results OFF this server too (another machine or cloud storage). Back up the APP_KEY from .env separately and keep it safe:
# without it, encrypted ID numbers, KRA PINs and eTIMS keys in a backup cannot be read.
set -euo pipefail
APP="${1:?Usage: backup.sh /var/www/dms [backup_dir]}"; DEST="${2:-/var/backups/dms}"; STAMP="$(date +%Y%m%d-%H%M%S)"
mkdir -p "$DEST"; cd "$APP"
get() { grep -E "^$1=" .env | head -1 | cut -d= -f2- | sed -e 's/^"//' -e 's/"$//'; }
case "$(get DB_CONNECTION)" in
  mysql|mariadb) MYSQL_PWD="$(get DB_PASSWORD)" mysqldump --single-transaction --quick -h "$(get DB_HOST)" -P "$(get DB_PORT)" -u "$(get DB_USERNAME)" "$(get DB_DATABASE)" | gzip > "$DEST/db-$STAMP.sql.gz" ;;
  sqlite) cp "$(get DB_DATABASE)" "$DEST/db-$STAMP.sqlite" ;;
  *) echo "Unsupported DB_CONNECTION"; exit 1 ;;
esac
tar -czf "$DEST/files-$STAMP.tar.gz" -C "$APP" storage/app
chmod 600 "$DEST"/*-"$STAMP"*
find "$DEST" -type f -mtime +14 -delete    # keep two weeks here
echo "Backup saved in $DEST ($STAMP)"
