#!/bin/bash
#This script creates a new subvolume for a machine config, setting up the
#corresponding snapshot directory for it.
#
#The first positional argument is the path of the machine config directory to
#create, specified as a relative or absolute path.
#
#The second optional positional argument is a source directory from which to
#copy the contents into the new machine config directory.
#
#If the -m option is specified, the source directory will be deleted afterwards.
#
#The -r option specifies an alternate collection root other than the one
#containing this script.

set -e
. "`dirname $0`/bootscriptfunctions.sh"

OSM_ALT_ROOT=""
unset move
while [ x"$1" != x ]
do
	case "$1" in
		-m)
			move=true
			;;
		-r)	shift
			OSM_ALT_ROOT="$1"
			;;
		*)	break
			;;
	esac
	shift
done

source_emulator_functions _snapshot

if [ x"$1" = x ]
then
	echo "usage: `basename $0`: [-m] [-r <root>] <machine config directory> [source directory]" >&2
	panic "no machine config path specified"
fi

new_config_path="`realpath -m $1`"

check_config_parent_dir "$new_config_path"

if ! echo "$new_config_path" | grep -q '_config$'
then
	panic "$new_config_path does not have a name ending in _config"
fi

if [ -e "$new_config_path" ]
then
	panic "$new_config_path already exists"
fi

parent_dir="`dirname $new_config_path`"

config_short_name="`basename $new_config_path | sed 's/_config$//'`"
snap_dir="$OSM_SNAP_ROOT/$config_short_name"
if [ -e "$snap_dir" ]
then
	panic "Snapshot directory $snap_dir already exists"
fi

if ! mkdir -p "$parent_dir"
then
	panic "cannot create parent directory for $new_config_path"
fi

if ! is_btrfs_path "$parent_dir"
then
	panic "parent directory of $new_config_path not on a BTRFS volume"
fi

if ! btrfs -q subvolume create "$new_config_path"
then
	panic "cannot create subvolume at $new_config_path"
fi

fix_uid_and_gid "$new_config_path"

if [ x"$2" != x ]
then
	shopt -s dotglob
	if [ "$move" ]
	then
		mv $2/* $new_config_path
		rmdir $2
	else
		cp -R --preserve=all $2/* $new_config_path
	fi
fi

mkdir -p "$snap_dir/_info"
ln -s "$new_config_path" "$snap_dir/_orig_path"
fix_uid_and_gid -R "$snap_dir"
