#!/bin/bash
# vim: ts=4 sw=4 ai noet
# $Id$
#
# vzpkgcache - create cached tarball for OS packages.
#
# Copyright (C) 2008, Robert Nelson. Licensed under GPLv2.
# By Robert Nelson.
#
# Portions originally:
# Copyright (C) 2005 by SWsoft. Licensed under QPL.
# By Kir Kolyshkin.

TOOLDIR=/usr/share/vzpkg2
#DEBUG_LEVEL=4

. ${TOOLDIR}/functions

log4 Started $0 $*

function usage() {
        cat << USAGE_EOF 1>&2
Usage:	$PROGNAME [-f|--force] [-n|--no-pkg-cacher] [osname ...] -- create/update OS cache(s)
	$PROGNAME -r|--remove osname [...]  -- remove OS cache(s)
	$PROGNAME -h|--help                 -- see this
USAGE_EOF
        exit $1
}

FORCE=""
NO_PKG_CACHER=""
REMOVE=""

while test $# -gt 0; do
	case $1 in
		-f|--force)
			FORCE="-f"
			shift
			;;
		-n|--no-pkg-cacher)
			NO_PKG_CACHER="-n"
			shift
			;;
		-r|--remove)
			REMOVE="-r"
			shift
			;;
		-h|-?|--help)
			usage 0
			;;
		-*)
			echo "Error: unknown option: $1" 1>&2
			usage 1
			;;
		*)
			break
			;;
	esac
done

TEMPLATE=`get_vz_var TEMPLATE`

if test $# -gt 0; then
	# Have list of OS templates from cmdline
	ALLTMPL=$*
	for T in $ALLTMPL; do
		FT=`ost2full $T` || abort "OS template $T not found"
		set $FT
		TNAME=$1-$2-$4-$3
		check_ost_exists $1 $2 $3 $4 ||
			abort "OS template $T ($TNAME) not found"
		OST_LIST="$OST_LIST $TNAME"
	done
else
	# Sanity check -- refuse to remove all OS templates
	if test "x$REMOVE" != "x"; then
		cat << R_EOF 1>&2
Error: refusing to remove all OS caches. Please specify OS name(s)
which cache(s) you want to remove and re-run, e.g. $PROGNAME -r myos-3.1
R_EOF
		usage 1
	fi
	log5 "TEMPLATE=$TEMPLATE"

	OST_LIST=`get_all_os_templates`
fi

test -z "$OST_LIST" && abort "No osnames given/found."

# Do the cache
for OS in $OST_LIST; do
	log4 "Calling cache-os $FORCE $NO_PKG_CACHER $REMOVE $OS"
	$TOOLDIR/cache-os $FORCE $NO_PKG_CACHER $REMOVE $OS
done
