#!/bin/sh

if [ "$1" = "--help" ]; then
	cat <<EOF
usage: vbuilder create <options>

options:
  --help                   show this text
  -n, --name <container>   name of environment (required)
  -v, --version <version>  version of environment
  -a, --arch <arch>        architecture of environment
  -o, --overlay            use overlayfs

EOF
	exit 0
fi

LIBEXECDIR="/usr/libexec/vbuilder"
DATADIR="/usr/share/vbuilder"
CACHEDIR="/var/cache/vbuilder"

CONTAINER=""
INSTROOT=""
OVERLAY=0

if grep -q VineSeed /etc/vine-release; then
	VERSION="VineSeed"
else
	VERSION=$(/etc/vine-release | awk '{print $3;}' | sed -e 's/\..*$//')
fi
ARCH=$(uname -m)
if [ "$ARCH" != "x86_64" ]; then
	ARCH="i386"
fi
HOST_ARCH=$ARCH

while [ $# -gt 0 ]; do
	case $1 in
		-n|--name)
			shift
			CONTAINER=$1
			;;
		-v|--version)
			shift
			VERSION=$1
			;;
		-a|--arch)
			shift
			ARCH=$1
			;;
		-o|--overlay)
			OVERLAY=1
			;;
	esac

	shift
done

if [ "$CONTAINER" = "" ]; then
	echo "no container name was not specified." >&2
	exit 1
fi

if [ "$VERSION" = "" ]; then
	echo "version was not specified." >&2
	exit 1
fi

if [ "$ARCH" = "" ]; then
	echo "arch was not specified." >&2
	exit 1
fi

if [ "$HOST_ARCH" != "x86_64" -a "$ARCH" != "$HOST_ARCH" ]; then
	echo "cannot create with $ARCH on $HOST_ARCH." >&2
	exit 1
fi

if [ ! -d $DATADIR/defs/$VERSION ]; then
	echo "invalid version was specified." >&2
	exit 1
fi

if [ ! -d $DATADIR/defs/$VERSION/$ARCH ]; then
	echo "invalid architecture was specified." >&2
	exit 1
fi

CONTAINER_PATH="/var/lib/lxc/$CONTAINER"
OVERLAYFS="$CONTAINER_PATH/overlay"

if [ -d $CONTAINER_PATH ]; then
	echo "$CONTAINER already exists." >&2
	exit 1
fi

if ! lxc-create -n $CONTAINER -t none; then
	echo "lxc-create was failed." >&2
	exit 1
fi

if [ $OVERLAY -ne 0 ]; then
	INSTROOT="$CONTAINER_PATH/rootfs.lower"
	mkdir -p $OVERLAYFS
else
	INSTROOT="$CONTAINER_PATH/rootfs"
fi

if [ ! -d $INSTROOT/usr ]; then
	$LIBEXECDIR/install-env install $INSTROOT $VERSION $ARCH vbuilder
	touch $INSTROOT/lxcroot
fi

$DATADIR/defs/$VERSION/$ARCH/post-install $CONTAINER $INSTROOT $VERSION $ARCH $DATADIR $OVERLAY vbuilder
