#!/bin/bash

SLEEP_MAX_TIME=15
RUN_TIME=1
SYSTEM_MAX_LOAD=5

source /etc/profile

CONTEXT=$1 
if [[ ! -d /proc/virtual/$CONTEXT ]] ; then
	echo "Context $CONTEXT does not exist"
	exit 1
fi

VCONTEXT=`which vcontext`
if [[ "$VCONTEXT" == "" ]] ; then
	echo "command vcontext not found"
	exit 2
fi
VKILL=`which vkill`
if [[ "$VKILL" == "" ]] ; then
	echo "command vkill not found"
	exit 2
fi

PID=$2
if ! vcontext --migrate  --xid $CONTEXT -- [ -d /proc/$PID ] ; then
	echo "PID $PID does not exist in context $CONTEXT"
	exit 3
fi
CMDLINE=`vcontext --migrate  --xid $CONTEXT -- cat /proc/$PID/cmdline`

while [ 1 ] ; do
	if ! vcontext --migrate  --xid $CONTEXT -- [ -d /proc/$PID ] ; then
		echo "Process $PID in context $CONTEXT has finished running - $CMDLINE"
		if [[ -f /var/run/throttler/$PID ]] ; then
			rm -f /var/run/throttler/$PID
		fi
		exit 0
	fi
	SYSTEM_LOAD=`uptime | cut -d ':' -f 5 | cut -d '.' -f 1`
	if [[ "$SYSTEM_LOAD" == "" ]] ; then
		SYSTEM_LOAD=`uptime | cut -d ':' -f 4 | cut -d '.' -f 1`
	fi
	if [[ "$SYSTEM_LOAD" != "" ]] ; then
		SLEEP_MAX_TIME=$((SYSTEM_LOAD*3))
		if (( $SYSTEM_LOAD > $SYSTEM_MAX_LOAD )) ; then
			SLEEP_TIME=9 #hardcoded 90%
			vkill --xid $CONTEXT -s STOP $PID
			sleep $SLEEP_TIME
			vkill --xid $CONTEXT -s CONT $PID
		fi
	fi
	sleep $RUN_TIME
done

