#!/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

VEX_BACKUP_DIR="${VEX_BACKUP_DIR:-/root/vexon-pool-backups}"
VEX_BACKUP_RETENTION_DAYS="${VEX_BACKUP_RETENTION_DAYS:-14}"

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

if ! [[ "$VEX_BACKUP_RETENTION_DAYS" =~ ^[0-9]+$ ]]; then
  echo "VEX_BACKUP_RETENTION_DAYS must be an integer, got: $VEX_BACKUP_RETENTION_DAYS" >&2
  exit 1
fi

install -d -m 700 "$VEX_BACKUP_DIR"

stamp="$(date +%Y%m%d-%H%M%S)"
archive="$VEX_BACKUP_DIR/vexon-pool-production-${stamp}.tar.gz"

bash scripts/backup-production.sh "$archive"

if (( VEX_BACKUP_RETENTION_DAYS > 0 )); then
  find "$VEX_BACKUP_DIR" \
    -type f \
    -name 'vexon-pool-production-*.tar.gz' \
    -mtime "+${VEX_BACKUP_RETENTION_DAYS}" \
    -delete
fi

latest="$VEX_BACKUP_DIR/latest.tar.gz"
ln -sfn "$(basename "$archive")" "$latest"
chmod 600 "$archive"

echo "Backup complete: $archive"
echo "Latest symlink: $latest"
