#!/usr/bin/env bash
# ============================================================
# HalaVoice server — WHOLE-ACCOUNT backup (all sites' DBs + settings)
#
# The cPanel account home is ~201G (> free disk), so this does NOT
# tar the site code locally. Instead it captures the SMALL, critical
# stuff on the server:
#   - every PostgreSQL database (+ roles/globals)   → databases/pg/
#   - every MySQL database                          → databases/mysql/
#   - cPanel account settings, DNS zones, cron      → configs.tar.gz
#   - a MANIFEST of all sites + DBs + sizes
# …and prints the exact rsync command to pull the site CODE straight
# to your own machine (no server-side staging needed).
#
# Run as root (needs postgres/mysql/cpanel config access).
#   sudo /home/ashraffarid2010/halavoice.store/ops/server-backup.sh
# Output: backups/server-<TS>/  (chmod 700 — contains secrets & data)
# ============================================================
set -uo pipefail

REPO_ROOT="/home/ashraffarid2010/halavoice.store"
ACCT="ashraffarid2010"
HOMEDIR="/home/$ACCT"
TS="$(date -u +%Y%m%d-%H%M%S)"
DEST="$REPO_ROOT/backups/server-$TS"
ENV_FILE="$REPO_ROOT/.env"

log(){ echo -e "\033[1;36m[srv-backup]\033[0m $*"; }
ok(){ echo -e "\033[1;32m[ ok ]\033[0m $*"; }
warn(){ echo -e "\033[1;33m[warn]\033[0m $*" >&2; }

[ "$(id -u)" = 0 ] || { echo "run as root (sudo)"; exit 1; }
mkdir -p "$DEST/databases/pg" "$DEST/databases/mysql"
chmod -R 700 "$DEST"

# ---- PostgreSQL: all databases + globals via the superuser in .env ----
log "Dumping PostgreSQL databases…"
PG_SUPER="$(grep '^EVOLUTION_DB_URL=' "$ENV_FILE" 2>/dev/null | cut -d= -f2- | sed -E 's#/[^/]+$#/postgres#')"
if [ -n "$PG_SUPER" ]; then
  PGPW="$(echo "$PG_SUPER" | sed -E 's#.*://[^:]+:([^@]+)@.*#\1#')"
  PGHOST="$(echo "$PG_SUPER" | sed -E 's#.*@([^:/]+).*#\1#')"
  PGUSER="$(echo "$PG_SUPER" | sed -E 's#.*://([^:]+):.*#\1#')"
  export PGPASSWORD="$PGPW"
  psql -U "$PGUSER" -h "$PGHOST" -tAc "SELECT datname FROM pg_database WHERE datistemplate=false AND datname<>'postgres' ORDER BY 1" 2>/dev/null \
    | while read -r db; do
        [ -n "$db" ] || continue
        pg_dump -U "$PGUSER" -h "$PGHOST" --no-owner --no-privileges "$db" 2>/dev/null | gzip -9 > "$DEST/databases/pg/$db.sql.gz"
        echo "    pg: $db ($(du -h "$DEST/databases/pg/$db.sql.gz" | cut -f1))"
      done
  pg_dumpall -U "$PGUSER" -h "$PGHOST" --globals-only 2>/dev/null | gzip -9 > "$DEST/databases/pg/_globals.sql.gz"
  unset PGPASSWORD
  ok "PostgreSQL done ($(ls "$DEST/databases/pg" | wc -l) files)"
else
  warn "EVOLUTION_DB_URL (pg superuser) not in .env — skipping PostgreSQL"
fi

# ---- MySQL: all databases via /root/.my.cnf ----
log "Dumping MySQL databases…"
if HOME=/root mysql -N -e "SELECT 1" >/dev/null 2>&1; then
  HOME=/root mysql -N -e "SHOW DATABASES" 2>/dev/null \
    | grep -viE '^(information_schema|performance_schema|sys|mysql)$' \
    | while read -r db; do
        [ -n "$db" ] || continue
        HOME=/root mysqldump --single-transaction --routines --triggers --events "$db" 2>/dev/null | gzip -9 > "$DEST/databases/mysql/$db.sql.gz"
        echo "    mysql: $db ($(du -h "$DEST/databases/mysql/$db.sql.gz" | cut -f1))"
      done
  ok "MySQL done ($(ls "$DEST/databases/mysql" | wc -l) files)"
else
  warn "no MySQL root access (/root/.my.cnf) — skipping MySQL"
fi

# ---- Account settings: cPanel meta, DNS zones, cron, vhosts ----
log "Archiving account settings (cPanel meta, DNS, cron, vhosts)…"
CFG_TMP="$DEST/_cfg"; mkdir -p "$CFG_TMP"
cp -a /var/cpanel/users/$ACCT           "$CFG_TMP/cpanel-user"        2>/dev/null || true
cp -a /var/cpanel/userdata/$ACCT        "$CFG_TMP/cpanel-userdata"   2>/dev/null || true
cp -a /var/spool/cron/$ACCT             "$CFG_TMP/account-crontab"   2>/dev/null || true
# DNS zones for this account's domains
mkdir -p "$CFG_TMP/dns-zones"
grep -rhoE '^(main_domain|addon_domains|sub_domains|parked_domains):.*' /var/cpanel/userdata/$ACCT/main 2>/dev/null \
  | tr ', ' '\n' | grep -E '^[a-z0-9.-]+\.[a-z]+$' | sort -u \
  | while read -r d; do [ -f "/var/named/$d.db" ] && cp -a "/var/named/$d.db" "$CFG_TMP/dns-zones/" 2>/dev/null; done
# Apache/nginx vhost configs for the account
cp -a /etc/apache2/conf.d/userdata 2>/dev/null "$CFG_TMP/apache-userdata" || true
tar -C "$DEST" -czf "$DEST/configs.tar.gz" _cfg 2>/dev/null && rm -rf "$CFG_TMP"
ok "Settings: configs.tar.gz ($(du -h "$DEST/configs.tar.gz" 2>/dev/null | cut -f1))"

# ---- Manifest of all sites ----
log "Writing manifest…"
{
  echo "HalaVoice server backup — account: $ACCT — $(date -u +%FT%TZ)"
  echo "host: $(hostname)   IP: 203.161.35.97"
  echo
  echo "== SITES (dirs under $HOMEDIR) =="
  ls -d "$HOMEDIR"/*/ 2>/dev/null | sed "s#$HOMEDIR/##;s#/##"
  echo
  echo "== PostgreSQL databases =="; ls "$DEST/databases/pg" 2>/dev/null | sed 's/\.sql\.gz//'
  echo
  echo "== MySQL databases =="; ls "$DEST/databases/mysql" 2>/dev/null | sed 's/\.sql\.gz//'
} > "$DEST/MANIFEST.txt"
( cd "$DEST" && find . -type f -name '*.gz' -exec sha256sum {} \; > SHA256SUMS.txt 2>/dev/null || true )

# ---- rsync helper for the (too-big-to-stage) site code ----
cat > "$DEST/PULL-SITE-CODE.txt" <<EOF
# ============================================================
# Pull ALL site code + this DB/config backup to YOUR machine.
# Run these FROM YOUR OWN COMPUTER (not the server). ~201G of code,
# so it streams directly with no server-side staging. Resumable.
# ============================================================

# 1) the small DB dumps + settings from this backup:
rsync -avz --progress \\
  ashraffarid2010@203.161.35.97:$DEST/  ~/halavoice-server-backup/db-and-config/

# 2) all site code + settings (excludes only regenerable deps/caches):
rsync -avz --progress --partial \\
  --exclude 'node_modules/' --exclude '.git/' --exclude '*/cache/' \\
  --exclude '*.log' --exclude 'logs/' --exclude '.npm/' --exclude '.cache/' \\
  ashraffarid2010@203.161.35.97:$HOMEDIR/  ~/halavoice-server-backup/sites/

# (add   --exclude 'models/'   to skip the 2.5G ML model if you don't need it)
# To include uploads/media, keep the command as-is. Re-run any time to sync changes.
EOF

chmod -R 700 "$DEST"
chown -R "$ACCT:$ACCT" "$DEST" 2>/dev/null || true
ok "Server backup ready: $DEST"
echo
echo "Next: read $DEST/PULL-SITE-CODE.txt and run those rsync commands FROM YOUR MACHINE."
