#!/bin/bash

#This script creates a snapshot of a guest VM. The VM name is specified as the
#base short name, without the directory or the _boot or _config suffixes.
#
#The -t option specifies a snapshot type tag, which may be anything, although
#some tags may be interpreted as having a special meaning (such as
#snapshot_delete refusing to delete snapshots with the "initial" type without
#the -f option).
#
#The -r option specifies an alternate collection root (i.e. the directory
#containing the .image_snapshots, images, and scripts directories).

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

OSM_ALT_ROOT=""

while [ x"$1" != x ]
do
	case "$1" in
		-t)
			shift
			snap_type="$1"
			if [ x"$snap_type" = x ]
			then
				panic "-t requires a snapshot type"
			fi
			;;
		-r)	shift
			OSM_ALT_ROOT="$1"
			;;
		*)
			break
			;;
	esac
	shift
done

source_emulator_functions _snapshot

if [ ! "$1" ]
then
	echo "no machine config specified" >&2
	echo "usage: `basename $0` [-t] [-r <root>] <machine config>"
	exit 1
fi

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

get_snapshot_paths $1

new_snapshot_path

if ! btrfs -q subvolume snapshot -r "$orig_path" "$new_snap_path"
then
	panic "creating new snapshot failed"
fi

snap_time="`basename $new_snap_path`"

if init_snapshot_info "$snap_type"
then
	echo "created snapshot `timestamp_to_display $snap_time`"
fi
