#!/bin/bash
# Limit compiler resources.
# Usage: dotimedcompile.sh [timelimit_secs [filesizelimit_kb]] <compile command and args>
# ex:  dotimedcompile.sh 30 128 /usr/bin/g++ -g -O2 -std=gnu++20 -static stress-test-compile-fill-stderr.cc
#       Would limit CPU time used by compiler to 30 seconds and file size generated to 128KB
# ex:  dotimedcompile.sh 30 /usr/bin/g++ -g -O2 -std=gnu++20 -static stress-test-compile-fill-stderr.cc
#       Would limit CPU time used by compiler to 30 seconds
# Note: the stderr channel of compilers is routed to PC2 via a pipe, as a result, its size limit can only
#       be enforced by PC2 itself.  The filesize limit here is for object/executable files generated by the compilers.
# Note2: Tobi from DOMjudge indicates that the file limit should be on the order of 2GB!  This is because the RAM
#       limit for submissions by default is 2GB.  If someone uses a static data section in the program of 2GB, the resulting
#       executable will be 2GB in size.  (sigh)
# Note3: Compiler command can not consist solely of numbers or it will be interpretted as a timelimit or file size limit
#       unless both a time and file size limit are supplied as well.
#
timelimit="$1"
sizelimit="$2"

# If first arg is a number, it's the timeout in seconds
if [[ "$timelimit" =~ ^[1-9][0-9]*$ ]]
then
	ulimit -t $timelimit
	shift
	# If second argument is a number, its the max filesize.
	if [[ "$sizelimit" =~ ^[1-9][0-9]*$ ]]
	then
		ulimit -f $sizelimit
		shift
	fi
fi
# Just exec the original command (albeit, possibly shifted)
exec "$@"
