#!/bin/bash

# Timeout.
timeout=20   # 20 seconds
# Interval between checks if the process is still alive.
interval=1
# Delay between posting the SIGTERM signal and destroying the process by SIGKILL.
delay=0

command=${0:0:${#0}-7}

# kill -0 pid   Exit code indicates if a signal may be sent to $pid process.
(
    ((t = timeout))

    while ((t > 0)); do
        sleep $interval
        kill -0 $$ || exit 0
        ((t -= interval))
    done

    # Be nice, post SIGTERM first.
    # The 'exit 0' below will be executed if any preceeding command fails.
    kill -s SIGTERM $$ && kill -0 $$ || exit 0
    sleep $delay
    kill -s SIGKILL $$
) 2> /dev/null &

exec $command $@
