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

# ---- CONFIG ----
UTM_DIR="$HOME/Library/Containers/com.utmapp.UTM/Data/Documents"
VM_NAME="Work.utm"

REMOTE_HOST="rhea.local"
REMOTE_DIR="/tank/backups/utm"

KEEP=5
DATE="$(date +%Y-%m-%d_%H-%M-%S)"

BASENAME="${VM_NAME%.utm}_$DATE"
ARCHIVE="/tmp/$BASENAME.tar.gz"

# ---- SANITY CHECKS ----
if [[ ! -d "$UTM_DIR/$VM_NAME" ]]; then
  echo "ERROR: VM not found: $UTM_DIR/$VM_NAME"
  exit 1
fi

# Optional: refuse if VM might be running
if pgrep -f "$VM_NAME" >/dev/null; then
  echo "ERROR: VM appears to be running. Shut it down first."
  exit 1
fi

# ---- CREATE ARCHIVE ----
echo "Creating compressed archive..."
tar -C "$UTM_DIR" -czf "$ARCHIVE" "$VM_NAME"

# ---- COPY ----
echo "Uploading $ARCHIVE → $REMOTE_HOST:$REMOTE_DIR/"
scp "$ARCHIVE" "$REMOTE_HOST:$REMOTE_DIR/"

# ---- REMOTE ROTATION ----
echo "Pruning old backups on remote (keeping last $KEEP)..."

ssh "$REMOTE_HOST" "
  ls -dt $REMOTE_DIR/${VM_NAME%.utm}_*.tar.gz 2>/dev/null \
  | tail -n +$((KEEP + 1)) \
  | xargs -r rm -f
"

# ---- CLEANUP ----
rm -f "$ARCHIVE"

echo "Backup complete."

