#!/bin/bash
#
# This script reserves access to a machine so that a user can run arbitrary
# programs on the machine.
#
# reqparam value The number of minutes to lease the machine -- leases can be renewed
# optparam value The e-mail address to send lease expiration notices to
#

. /etc/autobench.conf || . functions

function warn_helper () {
  # Two argument, command to run, and minutes left
  eval $1 <<-EOF
	There are $2 minutes remaining in your lease.
	
	To increase the amount of time remaining in your lease, run the renew
	command in the autobench directory ($AUTODIR/scripts/)
	
	If you are done with the machine, run the release command in the autobench
	directory
	EOF
}

function warn() {
  # warn() time_left [e-mail]
  warn_helper wall $1
  if [ $# -gt 1 ]; then
    warn_helper "mail -s 'Lease expiration Notice' $2" $1
  fi
}

function mysleep() {
  # So we can redirect stderr
  sleep $(($1*60)) &
  # sleep $1 & # For testing
  PID="$!"
  echo $PID > $TMPDIR/user-access/sleep.pid
  wait $PID
  rc=$?
  rm $TMPDIR/user-access/sleep.pid
  return $rc
}

if [ $# -lt 1 ]; then
  echo "You must specify the number of minutes to get access to the machine"
  exit 1
fi

getcommand renew
getcommand release

mkdir -p $TMPDIR/user-access/
echo $1 > $TMPDIR/user-access/lease-time
date > $TMPDIR/user-access/lease-start

# They may renew the lease forever -- though we don't want them to.
while true; do
  if [ "$START" != "`cat $TMPDIR/user-access/lease-start`" ]; then
    REMAINING_TIME=`cat $TMPDIR/user-access/lease-time`
    START=`cat $TMPDIR/user-access/lease-start`
    if [ 0 -eq $REMAINING_TIME ]; then
      break
    fi
  fi

  if [ $REMAINING_TIME -gt 120 ]; then
    SLEEP_TIME=$(($REMAINING_TIME/2))
  elif [ $REMAINING_TIME -gt 60 ]; then
    SLEEP_TIME=$(($REMAINING_TIME-60))
  elif [ $REMAINING_TIME -gt 30 ]; then
    SLEEP_TIME=$(($REMAINING_TIME-30))
  elif [ $REMAINING_TIME -gt 15 ]; then
    SLEEP_TIME=$(($REMAINING_TIME-15))
  elif [ $REMAINING_TIME -gt 5 ]; then
    SLEEP_TIME=$(($REMAINING_TIME-5))
  elif [ $REMAINING_TIME -gt 1 ]; then
    SLEEP_TIME=$(($REMAINING_TIME-1))
  elif [ $REMAINING_TIME -le 0 ]; then
    break
  else
    SLEEP_TIME=$REMAINING_TIME
  fi

  mysleep $SLEEP_TIME 2> /dev/null
  if [ $? -ne 0 ]; then
    continue
  fi
  REMAINING_TIME=$((REMAINING_TIME-$SLEEP_TIME))
  warn $REMAINING_TIME $2

done
rm -rf $TMPDIR/user-access/
