#!/usr/bin/env bash
# Enterprise Mail — backup script.
#
# Backs up: the PostgreSQL application database, this app's own
# configuration (backend/.env, frontend/.env — WITHOUT copying them
# world-readable), and Postfix/Dovecot configuration (config only, never
# mailbox content — mailbox backup is a much larger, host-specific decision
# left to you, e.g. via ZFS snapshots or a dedicated Maildir backup tool).
#
# Output goes to a directory that is NOT web-accessible and is chmod 700.
# You are responsible for shipping this off-host (rsync/rclone/etc.) — see
# docs/security.md for guidance; this script deliberately does not upload
# anywhere on your behalf.
#
# Usage: sudo ./scripts/backup.sh [output_dir]

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT_DIR="${1:-/var/backups/enterprise-mail}"
STAMP="$(date +%Y%m%d-%H%M%S)"
DEST="$OUT_DIR/$STAMP"

log() { printf '\033[1;34m[backup]\033[0m %s\n' "$1"; }

mkdir -p "$DEST"
chmod 700 "$OUT_DIR" "$DEST"

# --- 1. PostgreSQL database ---------------------------------------------------
if [[ -f "$ROOT_DIR/backend/.env" ]]; then
  DATABASE_URL="$(grep -E '^DATABASE_URL=' "$ROOT_DIR/backend/.env" | cut -d= -f2-)"
fi
if [[ -n "${DATABASE_URL:-}" ]]; then
  log "Dumping PostgreSQL database..."
  pg_dump --no-owner --format=custom "$DATABASE_URL" > "$DEST/enterprise_mail.dump"
  chmod 600 "$DEST/enterprise_mail.dump"
else
  log "DATABASE_URL not found in backend/.env — skipping database dump."
fi

# --- 2. Application configuration (secrets — kept 600, not shipped in plain) --
log "Archiving application configuration..."
mkdir -p "$DEST/config"
for f in backend/.env frontend/.env backend/.env.example frontend/.env.example; do
  [[ -f "$ROOT_DIR/$f" ]] && cp -a "$ROOT_DIR/$f" "$DEST/config/$(echo "$f" | tr '/' '_')"
done
chmod -R 600 "$DEST/config"/* 2>/dev/null || true

# --- 3. Mail server configuration (config only, not mailbox content) ---------
log "Archiving Postfix/Dovecot configuration..."
mkdir -p "$DEST/mailserver-config"
[[ -d /etc/postfix ]] && tar -czf "$DEST/mailserver-config/postfix.tar.gz" -C /etc postfix
[[ -d /etc/dovecot ]] && tar -czf "$DEST/mailserver-config/dovecot.tar.gz" -C /etc dovecot

# --- 4. Apache/systemd config for this app -----------------------------------
log "Archiving deploy/ (Apache + systemd templates as checked into the repo)..."
tar -czf "$DEST/deploy.tar.gz" -C "$ROOT_DIR" deploy

chmod -R 700 "$DEST"
log "Backup complete: $DEST"
log "IMPORTANT: this directory contains secrets (DB dump, .env files)."
log "  - It is NOT web-accessible and is chmod 700 — keep it that way."
log "  - Ship it off-host yourself (encrypted) — this script does not upload anywhere."
log "  - Mailbox content (Maildir) is NOT included — see docs/troubleshooting.md for Maildir backup options."
