#!/bin/bash

execdate() {
    local FILE=$1
    date -r $FILE +%s
}

havejobs() {
    jobs | wc -l
}

wait_term_or_recompile() {
    local EXECUTABLE=$1
    local PID=$2
    local THAN=$3
    local CURR=$THAN
    local RUNNING=`havejobs`
    
    while [ $RUNNING -ne 0 ]; do
        jobs >/dev/null # needed - whyever!
        # echo "RUNNING=$RUNNING"
        sleep 1
        CURR=`execdate $EXECUTABLE`
        if [ $CURR -gt $THAN ]; then
            kill -9 $PID
        fi
        RUNNING=`havejobs`
    done
}

# --------------------

main() {
    local EXECUTABLE=`which $1`
    shift
    local ARGS=$*

    if [ -z "$EXECUTABLE" ]; then
        echo "arb_rexec executable [arguments]"
        echo "Debugging script."
        echo "Calls 'executable'."
        echo "When 'executable' terminates -> call it again."
        echo "When 'executable' changes timestamp -> kill and call it again."
    else
        while true; do
            echo calling $EXECUTABLE $ARGS
            local STAMP=`execdate $EXECUTABLE`
            $EXECUTABLE $ARGS &
            local PID=$!
	    sleep 5
            wait_term_or_recompile $EXECUTABLE $PID $STAMP
        done
    fi
}

main $*
