#!/bin/bash

# This script launches another script with a given timeout
# After the timeout, the script will first receive a SIGTERM: exit code 124
# If this is not successful, the script will be killed (SIGKILL): exit code 137

if [ "$#" -lt 3 ]; then
	echo "Failure. Invalid number of arguments. Exiting"
	echo "Usage: scriptLauncher <watchdogTimeout> <rebootInsteadOfKillProcess> <scriptToBeLaunched> [<arg1>, <arg2>, ...]"
	exit 1
fi

function log() {
	echo "`date` $1"
}

TIMEOUT=$1
REBOOT=$2
SCRIPT_TO_BE_LAUNCHED=$3
ARGS_FOR_SCRIPT="${@:4}"
PID=$(cut -d' ' -f4 < /proc/self/stat)

if [ ! -f "$SCRIPT_TO_BE_LAUNCHED" ]; then
  log "Failure. Script ${SCRIPT_TO_BE_LAUNCHED} does not exist. Exiting"
	exit 1
fi

log "Process ${PID}: launching ${SCRIPT_TO_BE_LAUNCHED} with args ${ARGS_FOR_SCRIPT} and a timeout of ${TIMEOUT}s"
# Send sigterm after $TIMEOUT, kill 5 seconds after sigterm (if not yet exited)
timeout --kill-after=5 $TIMEOUT $SCRIPT_TO_BE_LAUNCHED $ARGS_FOR_SCRIPT
EXITCODE=$?

log "Exit code: ${EXITCODE}."
#124 => exit on sigterm, 137 => exit on sigkill
if [ "$EXITCODE" -eq 124 ] ||  [ "$EXITCODE" -eq 137 ]; then
  log "Timeout."
  if [ "$REBOOT" = true ]; then
    # Add short sleep to make sure io buffers are flushed
    log "Rebooting in 5s."
    sleep 5
    timeout --kill-after=5 5 /bin/sync
    sudo reboot
  fi
fi

exit $EXITCODE