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

out="${1:-/root/vexon-pool-backup.tar.gz}"
workdir="$(mktemp -d /tmp/vexon-pool-backup.XXXXXX)"
trap 'rm -rf "$workdir"' EXIT

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [[ -f "$repo_root/.env" ]]; then
  set -a
  # shellcheck source=/dev/null
  source "$repo_root/.env"
  set +a
fi

VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_WEB_DIR="${VEX_WEB_DIR:-$VEX_POOL_ROOT/web}"
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}"

mkdir -p "$workdir/mysql" \
  "$workdir/root-dot-vexond" \
  "$workdir/root-dot-vexonwallet" \
  "$workdir/var-stratum-config" \
  "$workdir/var-web" \
  "$workdir/etc-vexon-pool"

db_name="${POOL_DB_NAME:-vexonpool}"

if mysql -uroot -e "USE \`$db_name\`;" >/dev/null 2>&1; then
  mysqldump -uroot --single-transaction --routines --events "$db_name" | gzip > "$workdir/mysql/vexonpool.sql.gz"
else
  echo "Database $db_name does not exist yet; skipping database dump."
fi

if [[ -d "$VEX_NODE_APPDATA" ]]; then
  rsync -a --exclude='data/' --exclude='logs/' "$VEX_NODE_APPDATA/" "$workdir/root-dot-vexond/"
fi

if [[ -d "$VEX_WALLET_APPDATA" ]]; then
  rsync -a --exclude='logs/' "$VEX_WALLET_APPDATA/" "$workdir/root-dot-vexonwallet/"
fi

if [[ -f "$VEX_STRATUM_CONFIG_DIR/vexon.conf" ]]; then
  cp -av "$VEX_STRATUM_CONFIG_DIR/vexon.conf" "$workdir/var-stratum-config/"
fi

if [[ -f "$VEX_WEB_DIR/serverconfig.php" ]]; then
  cp -av "$VEX_WEB_DIR/serverconfig.php" "$workdir/var-web/"
fi

if [[ -f /etc/vexon-pool/keys.php ]]; then
  cp -av /etc/vexon-pool/keys.php "$workdir/etc-vexon-pool/"
fi

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

echo "Created $out"
echo "This archive contains secrets, wallet data, and a database dump. Keep it private."
