#!/bin/bash
set -euo pipefail

# -------- Require root or re-exec with sudo --------
if [[ $EUID -ne 0 ]]; then
  echo "⚠️ This script must be run as root. Trying with sudo..."
  exec sudo "$0" "$@"
fi

# -------- Configuration --------
BCK_DST="/myshares/backup/udm"
BCK_SRC="/data/unifi/data/backup"
REMOTE_HOST="root@unifi.swallow-grue.ts.net"
HC_ID="i0l97V2pxm"
KUMA_PUSH_URL="https://uptime.noxs.me/api/push/$HC_ID"
APP_NAME="udm"
APP_BCK_CMD="scp"
RETENTION=7
TIMESTAMP=$(date +%F_%H-%M)
ARCHIVE_NAME="backup_${TIMESTAMP}"
TMP_DIR="/tmp/${APP_NAME}_backup_$TIMESTAMP"

# -------- Functions --------
notify_kuma() {
  local status=$1
  local msg="Uptime-Kuma notification ($status)"
  if curl -fsS -m 10 --retry 3 -X GET "${KUMA_PUSH_URL}${status}" > /dev/null; then
    echo "✅ $msg sent."
  else
    echo "⚠️ Failed to send $msg."
  fi
}

abort() {
  echo "❌ Error: $1"
  rm -rf "$TMP_DIR"
  notify_kuma "?status=down"
  exit 1
}

# -------- Preparation --------
echo "📦 Dumping $APP_NAME database from $REMOTE_HOST..."
mkdir -p "$TMP_DIR" "$BCK_DST"

# -------- Test SSH connection --------
echo "🔌 Testing SSH connection to $REMOTE_HOST..."
if ! ssh -o BatchMode=yes -o ConnectTimeout=10 "$REMOTE_HOST" true 2>/dev/null; then
  abort "SSH connection to $REMOTE_HOST failed."
fi

# -------- Backup --------
echo "⬇️ Copying backup files via $APP_BCK_CMD..."
if ! $APP_BCK_CMD -prv "$REMOTE_HOST:$BCK_SRC" "$TMP_DIR"; then
  abort "$APP_BCK_CMD command failed."
fi

echo "✅ $APP_BCK_CMD command successful."

# -------- Compression --------
TAR_FILE="${BCK_DST}/${ARCHIVE_NAME}.tar.gz"
tar -czf "$TAR_FILE" -C "$TMP_DIR" .
echo "✅ Archive created: $TAR_FILE"

# -------- Cleanup --------
rm -rf "$TMP_DIR"

# -------- Notify success --------
notify_kuma ""

# -------- Rotation --------
echo "♻️ Applying retention policy (keep last $RETENTION backups)..."
cd "$BCK_DST"
ls -1dt backup_*.tar.gz 2>/dev/null | tail -n +$((RETENTION + 1)) | xargs -r rm -f
echo "✅ Rotation complete."