#!/usr/bin/env bash
# mBlog — take a full backup (database + files) before deploying.
# Usage:  PROJECT_ROOT=/var/www/mblog ./backup.sh
set -euo pipefail

PROJECT_ROOT="${PROJECT_ROOT:-/var/www/mblog}"
BACKUP_DIR="${BACKUP_DIR:-$PROJECT_ROOT/backups}"
DB_NAME="${MBLOG_DB_NAME:-mblog}"
DB_USER="${MBLOG_DB_USER:-mblog_app}"
DB_HOST="${MBLOG_DB_HOST:-127.0.0.1}"
DB_PORT="${MBLOG_DB_PORT:-5432}"

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

echo "==> Dumping database '$DB_NAME'"
PGPASSWORD="${MBLOG_DB_PASS:-}" pg_dump -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -Fp "$DB_NAME" \
  | gzip > "$BACKUP_DIR/db-$ts.sql.gz"

echo "==> Archiving files"
# Include whichever of these exist (app/config may not exist on the very first deploy)
paths=()
for d in web app config scripts; do [ -e "$PROJECT_ROOT/$d" ] && paths+=("$d"); done
tar -czf "$BACKUP_DIR/files-$ts.tar.gz" -C "$PROJECT_ROOT" "${paths[@]}"

echo "==> Done. Backups:"
ls -lh "$BACKUP_DIR"/*"$ts"*
cat <<EOF

Restore database:
  gunzip -c "$BACKUP_DIR/db-$ts.sql.gz" | psql -h $DB_HOST -p $DB_PORT -U $DB_USER $DB_NAME
Restore files:
  tar -xzf "$BACKUP_DIR/files-$ts.tar.gz" -C "$PROJECT_ROOT"
EOF
