#!/bin/bash
# Create Snapshots Before Making Changes
# Usage: ./snapshot-before-change.sh <VMID> [snapshot-name]

set -euo pipefail

VMID="${1:-}"
SNAPSHOT_NAME="${2:-pre-change-$(date +%Y%m%d-%H%M%S)}"

if [[ -z "$VMID" ]]; then
    echo "Usage: $0 <VMID> [snapshot-name]"
    echo "Example: $0 106 pre-upgrade-20241219"
    exit 1
fi

if ! command -v pct >/dev/null 2>&1; then
    echo "Error: pct command not found. This script must be run on Proxmox host."
    exit 1
fi

if [[ $EUID -ne 0 ]]; then
    echo "Error: This script must be run as root"
    exit 1
fi

echo "Creating snapshot '$SNAPSHOT_NAME' for container $VMID..."
if pct snapshot "$VMID" "$SNAPSHOT_NAME"; then
    echo "✓ Snapshot created successfully"
    echo "  To restore: pct rollback $VMID $SNAPSHOT_NAME"
    echo "  To list: pct listsnapshot $VMID"
else
    echo "✗ Failed to create snapshot"
    exit 1
fi
