#!/bin/bash
. "`dirname $0`/bootscriptfunctions.sh"
OSM_NO_ALT_ROOT="true"
source_emulator_functions _snapshot

get_package_version()
{
	apt-cache show $1 2>/dev/null | grep '^Version: ' | sort | tail -n 1 | sed 's/^Version: //g'
}

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

if ! check_guest_lock -n $1
then
	panic "Machine config $1 currently in use"
fi

if [ -d $OSM_SNAP_ROOT/$1 ]
then
	get_snapshot_paths -p $1
	fix_subvolume "$orig_path"
	md5sums="$snap_config_root/_last_pkg_md5sums"
	if [ -f "$md5sums" ] && ! md5sum --status -c "$md5sums"
	then
		snapshot_create -t final_pre_upgrade $1
	else
		package_basename="`basename $1 | tr _ -`"
		package_prefix="os-museum-machine-${package_basename}"
		info_version="`get_package_version ${package_prefix}-info`"
		image_version="`get_package_version ${package_prefix}-image`"
		if [ x"$info_version" != x -a x"$image_version" = x ]
		then
			if [ "$info_version" -gt "$image_version" ]
			then
				snapshot_create -t initial $1
			fi
		fi
	fi
	previous_config_path="`realpath $snap_config_root/_orig_path`"
	if [ x"$previous_config_path" != x"$2" ]
	then
		snapshot_move_subvolume "$1" "$2"
	fi
else
	snapshot_init_subvolume "$2"
fi
