#!/usr/bin/env bash
_scriptname="timeout"
set -u

if (( $# < 2 )) || [ -z "${1:-}" ] || [[ "$1" == *[!0-9]* ]]; then
	echo "Usage:   ${_scriptname} <timeout_in_seconds> <command>" >&2
	echo "Example: ${_scriptname} 2 sleep 3 || echo timeout" >&2
	exit 0
fi

function cleanup
{
	trap : CHLD EXIT

	# attempt to kill the timeout - kill the job if we fail
	if ! kill -SIGTERM %1 2>/dev/null; then
		kill -SIGTERM %2 2>/dev/null && exit 128
	fi

	# get exit status from job and exit
	wait %2
	exit $?
}

set -m								# enable job control
timeout=$1 && shift					# first param is timeout in seconds
trap cleanup CHLD EXIT				# cleanup after timeout or command
sleep $timeout &					# start the timeout
"$@"								# start the job
