#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

POOL_DB_NAME="${POOL_DB_NAME:-vexonpool}"
VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_WEB_DIR="${VEX_WEB_DIR:-$VEX_POOL_ROOT/web}"
VEX_DOCS_DIR="${VEX_DOCS_DIR:-$VEX_POOL_ROOT/docs}"
VEX_STRATUM_CONFIG_DIR="${VEX_STRATUM_CONFIG_DIR:-$VEX_POOL_ROOT/stratum-config}"
VEX_NODE_APPDATA="${VEX_NODE_APPDATA:-/root/.vexond}"
VEX_WALLET_APPDATA="${VEX_WALLET_APPDATA:-/root/.vexonwallet}"

out="${1:-/root/vexon-pool-production-$(date +%Y%m%d-%H%M%S).tar.gz}"
tmp="$(mktemp -d /tmp/vexon-pool-backup.XXXXXX)"

cleanup() {
  rm -rf "$tmp"
}
trap cleanup EXIT

if [[ "$(id -u)" != "0" ]]; then
  echo "Run as root so wallet files and server configs can be backed up." >&2
  exit 1
fi

mkdir -p "$tmp/mysql" "$tmp/config" "$tmp/appdata" "$tmp/web"

if command -v mysqldump >/dev/null 2>&1; then
  mysqldump -uroot --single-transaction --routines --events "$POOL_DB_NAME" | gzip > "$tmp/mysql/${POOL_DB_NAME}.sql.gz"
else
  echo "mysqldump is not installed." >&2
  exit 1
fi

for file in \
  "$VEX_WEB_DIR/serverconfig.php" \
  "/etc/vexon-pool/keys.php" \
  "$VEX_STRATUM_CONFIG_DIR/vexon.conf" \
  "$VEX_NODE_APPDATA/vexond.conf" \
  "$VEX_WALLET_APPDATA/vexonwallet.conf"; do
  if [[ -f "$file" ]]; then
    mkdir -p "$tmp/config$(dirname "$file")"
    cp -a "$file" "$tmp/config$file"
  fi
done

if [[ -d "$VEX_NODE_APPDATA" ]]; then
  mkdir -p "$tmp/appdata/root-dot-vexond"
  rsync -a --delete --exclude='logs' --exclude='data' "$VEX_NODE_APPDATA/" "$tmp/appdata/root-dot-vexond/"
fi

if [[ -d "$VEX_WALLET_APPDATA" ]]; then
  mkdir -p "$tmp/appdata/root-dot-vexonwallet"
  rsync -a --delete --exclude='logs' "$VEX_WALLET_APPDATA/" "$tmp/appdata/root-dot-vexonwallet/"
fi

if [[ -d "$VEX_DOCS_DIR" ]]; then
  rsync -a --delete "$VEX_DOCS_DIR/" "$tmp/web/docs/"
fi

cat > "$tmp/README.txt" <<'EOF'
Vexon Pool production backup.

This archive contains private operational data, including database rows, RPC
credentials, server configuration, and possibly wallet files. Keep it encrypted,
offline, and private. Do not commit it to GitHub or upload it to a public web
directory.
EOF

tar -czf "$out" -C "$tmp" .
chmod 600 "$out"

echo "Created $out"
echo "Keep this archive private. It may contain wallet data and live credentials."
