#!/bin/bash
#This script moves an existing subvolume for a machine config (specified as a
#base name without the parent directory) to a different location within the
#image directory (specified as a path including the parent directory).
#
#An alternate collection root can be specified with the -r option.

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

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

source_emulator_functions _snapshot

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

machine_config="`echo $1 | sed 's/_config$//g'`"

if [ x"$machine_config" = x ]
then
	panic "invalid machine config name specified"
fi

new_path="`realpath -m $2`"

check_config_parent_dir "$new_path"

#if ! realpath -m "$new_path" | grep -q "^$OSM_ALT_IMAGE_DIR"
#then
#	panic "new path $new_path not in image directory"
#fi

if ! echo "$new_path" | grep -q '_config$'
then
	panic "new path $new_path does not end in _config"
fi

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

get_snapshot_paths "$machine_config"

mkdir -p "`dirname $new_path`"
orig_path="`realpath $snap_config_root/_orig_path`"
mv "$orig_path" "$new_path"
rm "$snap_config_root/_orig_path"
ln -s "$new_path" "$snap_config_root/_orig_path"

new_short_name="`basename $new_path | sed 's/_config$//'`"
if [ x"$new_short_name" != x"$machine_config" ]
then
	mv "$snap_config_root" "$OSM_SNAP_ROOT/$new_short_name"
fi
