#!/bin/sh -e

export LC_ALL=C LANG=C LANGUAGE=C

PROG="${0##*/}"

# base directories
vzdir=/var/lib/vz/template
cache_dir=$vzdir/cache
TMPDIR=/var/lib/vz/template/tmp
profile_dir=/etc/spt/profiles/ovz

# base options
image_type="tgz"
build_name=
profile_name=

Info()
{
	printf %s\\n "$PROG: $*" >&2
}

verbose=
Verbose()
{
	[ -n "$verbose" ] || return 0
	Info "$*"
}

Fatal()
{
	printf %s\\n "$PROG: Fatal $*" >&2
	exit 1
}

show_usage()
{
	[ -z "$*" ] || Info "$*"
	printf %s\\n "Try \`$PROG --help' for more information." >&2
	exit 1
}

workdir=
exit_handler() 
{
	local rc=$?
	trap - EXIT
	[ ! -d "$workdir" ] || rm -rf -- "$workdir"
	exit $rc
}

create_cache()
{
	Info "Creating cache $OUT."
	spt ${image_type:+--image-type="$image_type"} \
        	${profile_dir:+--profile-dir="$profile_dir/$profile_name"} \
		$verbose $quiet \
		"$workdir"
}

show_help()
{
        [ -z "$*" ] || Info "$*"
	unset TMPDIR
        cat <<__EOF__
$PROG - make OpenVZ template cache of custom VE

Usage: $PROG [options]

Valid options are:
  --build=NAME		   build cache with name NAME.
  --profile=DIR            name of profile to use.
  -q, --quiet              try to be more quiet
  -v, --verbose            print a message from each action
  -h, --help               show this text and exit

Report bugs to http://bugs.altlinux.org/

__EOF__
    exit
}

TEMP=`getopt -n $PROG -o v,q,h -l build:,profile:,verbose,help,quiet -- "$@"` || show_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		--build) shift
		[ -z "$1" ] || build_name="$1"
		;;
		--profile) shift; profile_name="$1"
		;;
		-v|--verbose) verbose=-v
		;;
		-q|--quiet) quiet=-q
		;;
		-h|--help) show_help
		;;
		--) shift; break
		;;
		*) Fatal "Unrecognized option: $1"
		;;
	esac
	shift
done

[ ! -z $build_name ] || show_usage 'Cache name is not defined.'
[ -f "$profile_dir/$profile_name/ovz/config" ] || show_usage 'Profile in workdir not found. Please, init directories stucture first.'
. "$profile_dir/$profile_name/ovz/config"

trap exit_handler HUP PIPE INT QUIT TERM EXIT
workdir="$(mktemp -dt $PROG.XXXXXXXXX)"

create_cache &&
	Info "Cache $OUT make complete." ||
	Fatal "Cache $OUT make failed."

[ ! -f "$workdir/$OUT.tar.gz" ] ||
	cp -af "$workdir/$OUT.tar.gz" "$cache_dir/$build_name.tar.gz"
