#! /bin/sh

# Ask to use the TM

# Default priority is 100
# Default runtime is 10 minutes
priority=100
runtime=10

case $1 in

-p)	priority=$2
	shift
	shift
	;;

-*)	echo "usage: tmget [-p priority] [minutes]"
	exit 1
	;;
esac

case $# in

0)	;;

1)	runtime=$1
	;;

*)	echo "usage: tmget [-p priority] [minutes]"
	exit 1
	;;

esac

runtime=`expr $runtime '*' 60`

result=`tm acquire $priority $runtime`

case $result in

0)	;;

*)	owner=`tm getstatus1 | sed 's/:.*//'`
	echo $owner $result | awk '{printf "sorry, %s has it (priority %d) for %s more seconds\n", $1, $2, $3}'
	exit 1
	;;
esac

tm setstatus1 "$USER: using; priority $priority" 

t=`date +"%a %h %d %H %M %S"`
UNTIL=`echo $t $runtime | awk '
	{
	s=$6 + $7
	m=$5
	h=$4
	if(s > 59) {
		m += int(s/60)
		s %= 60;
		}
	if(m > 59) {
		h += int(m/60)
		m %= 60;
		}
	printf "%s %s %d %02d:%02d:%02d\n", $1, $2, $3, h, m, s
	}'`
	
tm setstatus2 "until: $UNTIL"
exit 0
