#!/bin/sh

if [ "$1" = "--help" ]; then
	cat <<EOF
usage: vbuilder reset -n <container>

options:
  --help  show this text

EOF
	exit 0
fi

CONTAINER=""
QUIET=0

while [ $# -gt 0 ]; do
	case $1 in
		-n|--name)
			shift
			CONTAINER=$1
			;;
		-q)
			# internal option
			shift
			QUIET=1
			;;
	esac

	shift
done

if [ "$CONTAINER" = "" ]; then
	echo "no environment specified." >&2
	exit 1
fi

if ! lxc-info -n "$CONTAINER" >/dev/null 2>&1; then
	echo "no such container." >&2
	exit 1
fi

LIBEXECDIR="/usr/libexec/vbuilder"
CACHEDIR="/var/cache/vbuilder"
CONTAINER_PATH=/var/lib/lxc/$CONTAINER

if [ -d $CONTAINER_PATH/rootfs.lower ]; then
	rm -rf $CONTAINER_PATH/overlay/{upper,work}
	rm -rf /dev/shm/vbuilder/$CONTAINER
else
	if [ $QUIET -ne 0 ]; then
		echo "cannot reset the container without overlayfs." >&2
		exit 1
	fi

	exit 0
fi

if ! lxc-wait -n $CONTAINER -t 3 -s STOPPED; then
	echo "container is busy." >&2
	exit 1
fi

