#!/bin/bash
# $Id: vzpkgls,v 1.3 2005/08/07 14:20:23 kir Exp $
#
# Utility to list either OS templates available on an Open Virtuozzo node,
# or an OS template installed into a given VPS. See usage() for info.
#
# Copyright (C) 2005, SWsoft. Licensed under QPL.
# By Kir Kolyshkin.


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

. ${TOOLDIR}/functions

function usage() {
	cat << _EOF_
Usage: $PROGNAME [-c|--cached]
       $PROGNAME <vpsid>
       $PROGNAME -h|--help
_EOF_
}

function list_ve() {
	# List VPS OS template
	STATUS=`$VZCTL status $VEID` || \
		abort "Can't get status for VPS $VEID: " \
			"vzctl status failed with code $?"
	echo $STATUS | grep -qw "exist" || abort "VPS $VEID not exist!"
	get_ve_os_template
	echo $OSTEMPLATE
}


while ! test -z $1; do
	case $1 in
		-h|--help)
			usage
			exit 0
			;;
		-c|--cached)
			CHECK_CACHE=1
			;;
		-q|--quiet)
			QUIET=1
			# This setting is currently makes no effect
			;;
		-o|--order)
			# For compatibility; just ignore
			;;
		*)
			# Is VPSID supplied?
			if echo $1 | egrep -q '^[1-9][0-9]*$'; then
				VEID=$1
				list_ve
				exit 0
			fi
			echo "Invalid arguments: $*" 1>&2
			usage
			exit 1
			;;
	esac
	shift
done


# List all OS templates installed
ALLTEMPLATES=`get_all_os_templates`
if test "x$CHECK_CACHE" != "x"; then
	# Check if these templates has a cache
	TEMPLATE=`get_vz_var TEMPLATE`
	CACHEDIR=`get_cache_dir`
	for T in $ALLTEMPLATES; do
		CACHE=$T.tar.gz
		if test -f $CACHEDIR/$CACHE; then
			TEMPLATES="$TEMPLATES $T"
		fi
	done
else
	TEMPLATES=$ALLTEMPLATES
fi
# Print all OS template names, one per line
echo $TEMPLATES | sed 's/[[:space:]]/\n/g'
