#!/bin/bash
# If the app restarts $RETRIES times with less than $RETRYTIMEOUT between restarts then give up
# If the app takes longer than $RETRYTIMEOUT to restart then set $RETRY counter to 0
# TODO: Start browser based on program output.  Start when "wthttp: started server: http://0.0.0.0:8080"
#       string is found.

RETRIES=5
RETRY=0
RETRYTIMEOUT=5

cd ~/g4dev/project/
echo $(pwd)
while [ $RETRY -lt $RETRIES ]
do
    time1=$(date +"%s")
    echo "Starting program, attempt " $i
    sudo setcap cap_net_bind_service=+ep ~/g4dev/project/bin/debug/project.exe
    #Start browser 4 seconds after app launches
    (sleep 4 && chromium-browser --incognito --kiosk http://0.0.0.0:8080) &
    ./rund 1>/dev/null
    time2=$(date +"%s")
    sleep 3 #Give time for browser to launch and get pid in case app crashes immediately
    #Kill browser after app is done
    BPID=$(ps | grep chromium | awk '{print $1}' | head -1) 
    sudo kill $BPID
    PRGTIME=$(($time2-$time1))
    echo "Program run time " $PRGTIME " seconds"
    #If program has been running for less than $RETRYTIMEOUT then increment retry
    #Fail when $RETRY equals $RETRIES
    if [ $PRGTIME -lt $RETRYTIMEOUT ]
    then
       RETRY=$[$RETRY+1]
    else
       RETRY=0
    fi
    echo "retry #" $RETRY
done
