#!/bin/sh
#
# Copyright (c) 2006 by Peter Williams
# All rights reserved
#
# Author: Peter Williams <pwil3058@bigpond.net.au>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

myusage_low () {
	echo "Usage:"
	echo -e "\twithcap [options] command [arguments ...]"
	echo -e "\twithcap -h"
	echo "Options:"
	echo -e "\t[-c <CPU rate soft cap>]"
	echo -e "\t[-C <CPU rate hard cap>]"
	echo -e "\t[-n <nice value>]"
}

myusage () {
	myusage_low
}

myhelp () {
	myusage_low
	echo
	echo -e "\t-c Set CPU usage rate soft cap"
	echo -e "\t-C Set CPU usage rate hard cap"
	echo -e "\t-n Set nice value"
	echo -e "\t-h Display this help"
}

cflag=
Cflag=
nflag=
hflag=
while getopts c:C:hn: name
do
	# no options after -h
	if [ ! -z "$hflag" ] ; then
		myusage
		exit 1
	fi

	# prevent duplicate arguments
	eval thisflag=\$${name}flag
	if [ ! -z "$thisflag" ] && [ "$thisflag" != "0flag" ];
	then
		echo -e "Error: multiple use of -$name option\n"
		myusage
		exit 1
	fi
	case $name in
	c)	if [ ! -z "`echo "$OPTARG" | grep '^[0-9][0-9]*$'`" ];
		then
			cflag=1
			soft_cap="$OPTARG"
		else
			echo -e "-c $OPTARG: positive integer expected"
			exit 2
		fi
		;;
	C)	if [ ! -z "`echo "$OPTARG" | grep '^[0-9][0-9]*$'`" ];
		then
			Cflag=1
			hard_cap="$OPTARG"
		else
			echo -e "-C $OPTARG: positive integer expected"
			exit 2
		fi
		;;
	h)	hflag=1
		;;
	n)	nflag=1
		nice="$OPTARG"
		echo "n seen"
		;;
	?)	myusage
		exit 1
		;;
	esac
done
shift `expr $OPTIND - 1`
if [ ! -z "$hflag" ]; then
	myhelp
	exit 0
fi
# must have some arguments after the options
if [ -z "$*" ]; then
	echo -e "Error: command expected\n"
	myusage
	exit 1
fi

if [ ! -z "$cflag" ]; then
	if ! echo $soft_cap > /proc/$$/task/$$/cpu_rate_cap; then
		echo "Error: setting soft cap of $soft_cap"
		exit 3
	fi
fi

if [ ! -z "$Cflag" ]; then
	if ! echo $hard_cap > /proc/$$/task/$$/cpu_rate_hard_cap; then
		echo "Error: setting hard cap of $hard_cap"
		exit 3
	fi
fi

if [ ! -z "$nflag" ]; then
	if ! renice $nice $$ > /dev/null; then
		echo "Error: setting nice of $nice"
		exit 3
	fi
fi

exec $*
