#!/bin/bash
# requires VirtualBox
VM="$1"
KEEP_DAYS="${2:-7}"
CUTOFF=$(date -d "$KEEP_DAYS days ago" +%Y%m%d)

if [[ -z "$VM" ]]; then
    echo "Usage: $0 <vm-name> [days-to-keep]"
    exit 1
fi

# Take a new snapshot
SNAP="auto-$(date +%Y%m%d)"
VBoxManage snapshot "$VM" take "$SNAP" --description "Automatic snapshot"

# Delete snapshots older than CUTOFF
VBoxManage snapshot "$VM" list --machinereadable \
    | grep "^SnapshotName" \
    | cut -d'"' -f2 \
    | grep "^auto-" \
    | while read -r name; do
        snap_date="${name#auto-}"
        echo "$snap_date $CUTOFF"
        if [[ "$snap_date" < "$CUTOFF" ]]; then
            VBoxManage snapshot "$VM" delete "$name"
        fi
    done
