#!/bin/sh
#
#
#    Scalix Public License
#
#
#    The contents of this file are subject to the Scalix Public License
#    Version 1.1 ("License"); you may not use this file except in
#    compliance with the License. You may obtain a copy of the License at
#
# 
#    http://www.scalix.com/community/licensing 
#
# 
#    Software distributed under the License is distributed on an "AS IS"
#    basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
#    the License for the specific language governing rights and limitations
#    under the License.
#
# 
#    The Original Code is Scalix Server. 
#    The Initial Developer of the Original Code is Scalix Corporation. 
#    Copyright (C) 2006 Scalix Corporation. 
#    All Rights Reserved.
#    Additional Copyrights may apply - see the notice in each file
#
#
#
#
#
# 

# Copyright (C) 2005 Scalix Corporation. All rights reserved.
#
################################################################
# This script is used by the Ubermanager to list the message storage using sxdu command.
################################################################
usage() {
	echo "usage:$0  -o ascend | descend -s wb | mb | all  -n num"
	exit 1
}
if [ "$#" -ne 6 ]
then
	usage
fi
#
# parse the arguments 
#
while getopts o:n:s: opt
do
	case "$opt" in 
		o) sortorder="$OPTARG" ;;
		s) sortedby="$OPTARG" ;;
		n) maxusers="$OPTARG" ;;
		[?]) usage;;
	esac
done
if [ "$sortedby" = "all" ]
then
	SXDU="/opt/scalix/bin/sxdu"
elif [ "$sortedby" = "wb" -o "$sortedby" = "mb" ]
then
	SXDU="/opt/scalix/bin/sxdu -a"
else
	usage
fi
#
# Construct the command to be executed
#
if [ "$sortorder" = "ascend" ]
then
	SORT="sort -n"
	LAST_BIT="tail -$maxusers"

elif [ "$sortorder" = "descend" ]
then
	SORT="sort -nr"
	LAST_BIT="head -$maxusers"
else
	usage
fi
#
# check the sorted by options
#
if [ "$sortedby" = "mb" -o "$sortedby" = "all" ]
then
	SORT=${SORT}k1
else
	SORT=${SORT}k2
fi
#
# Execute the command
#
$SXDU | $SORT | $LAST_BIT
#
# check status. If fails just skip it
#
if [ $? -ne 0 ]
then
	echo "[SX 500] Failed to obtain Message Store Usage"
	exit $?
fi
exit 0
