#!/bin/bash

#This script deletes a snapshot of a guest VM. The first positional argument is
#the VM name specified as the base short name, without the directory or the
#_boot or _config suffixes. The second argument is the snapshot timestamp,
#specified in local time, as displayed by snapshot_list.
#
#The -f option allows deleting a snapshot of the current installation revision
#with the "initial" type tag. Without it, such snapshots are not allowed to be
#deleted.
#
#The -r option specifies an alternate collection root (i.e. the directory
#containing the .image_snapshots, images, and scripts directories).



. "`dirname $0`/bootscriptfunctions.sh"

source_emulator_functions _snapshot_sudo
snapshot_cmd_sudo "$@"

OSM_ALT_ROOT=""
force_delete=""
while [ "$1" ]
do
	case "$1" in
		-f)
			force_delete="true"
			;;
		-r)	shift
			OSM_ALT_ROOT="$1"
			;;
		*)
			break
			;;
	esac
	shift
done

source_emulator_functions _snapshot


if [ x"$2" = x ]
then
	echo "usage: `basename $0` [-f] <machine config> <snapshot>"
	exit 1
fi

if ! acquire_guest_lock -n $1
then
	 panic "machine $1 currently running"
fi

get_snapshot_paths $1
get_machine_revision

timestamp_to_path $2

snap_revision="`get_snapshot_info $snap_time machine_info_revision`"
if [ x"$snap_revision" = "x-" ]
then
	snap_revision="`get_snapshot_info $snap_time machine_revision`"
fi
if [ x"$snap_revision" = "x-" ]
then
	snap_revision=0
fi
snap_type="`get_snapshot_info $snap_time snapshot_type`"

if [ x"$snap_type" = "xinitial" -a "$snap_revision" -ge "$machine_revision" -a x"$force_delete" = x ]
then
	panic "not deleting initial snapshot $snap_time"
fi

rm -rf "$snap_config_root/_info/$snap_time"
btrfs -q subvolume delete "$snap_config_root/$snap_time"
