#!/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 in_place
unset move
while [ x"$1" != x ]
do
	case "$1" in
		-i)	in_place=true
			;;
		-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" -a x"$in_place" = x ]
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
	if [ x"$in_place" = x ]
	then
		panic "Snapshot directory $snap_dir already exists"
	else
		exit 0
	fi
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

unset old_config_path

if [ x"$in_place" != x -a -d "$new_config_path" ]
then
	old_config_path="$new_config_path.$RANDOM"
	move=true
	mv "$new_config_path" "$old_config_path"
fi

if [ x"$2" != x ]
then
	if [ x"$old_config_path" != x ]
	then
		panic "both -i option and original path specified"
	fi
	old_config_path="$2"
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"$old_config_path" != x ]
then
	shopt -s dotglob
	if [ "$move" ]
	then
		rsync -av $old_config_path/. $new_config_path
		rm -rf $old_config_path
	else
		cp -R --preserve=all $old_config_path/* $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"
