#!/bin/bash
#This script reverts a machine config to a previous snapshot. The machine config
#name is specified as a base name without the _boot or _config suffix, and the
#snapshot is specified as a timestamp in local time as listed by snapshot_list.
#
#By default, this will create a snapshot of type pre_restore before restoring.
#The -n option disables this (in which case any changes are completely lost).
#
#The -t option overrides the type tag of the pre-restore snapshot to something
#other than pre_restore.
#
#The -r option specifies an alternate collection root.

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

source_emulator_functions _snapshot_sudo
snapshot_cmd_sudo "$@"

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

source_emulator_functions _snapshot

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

machine_name="$1"

if ! check_guest_lock -n $machine_name
then
	 panic "machine $machine_name currently running"
fi

get_snapshot_paths $machine_name

timestamp_to_path $2
snap_path="$snap_config_root/$snap_time"

if ! echo "$snap_time" | grep -q '^[0-9][0-9][0-9][0-9]'
then
	panic "invalid snapshot timestamp $snap_time"
fi

if ! is_btrfs_subvolume "$snap_path"
then
	panic "snapshot not a BTRFS subvolume"
fi

if [ "$preserve" -a -d "$orig_path" ]
then
	if [ x"$snap_type" = x ]
	then
		snap_type=pre_restore
	fi
	snapshot_create -r $OSM_ALT_ROOT -t $snap_type $machine_name
fi

acquire_guest_lock -n "$machine_name"

btrfs -q subvolume delete "$orig_path"

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

fix_uid_and_gid "$orig_path"
