#!/usr/bin/env bash
WORK_DIR=$1
if [ ! -n "${WORK_DIR}" ] ;then
    WORK_DIR="."
fi

echo "Restarting LaravelS..."
./bin/laravels stop
port=`netstat -ntlp | grep laravels | awk '{print $7}' | awk -F '/' '{print $1}'`
if [ -n "$port" ]; then
    kill -9 $port
    sleep 1
fi
./bin/laravels start -d -i

echo "Starting inotifywait..."
LOCKING=0

inotifywait --event modify --event create --event move --event delete -mrq   ${WORK_DIR}  | while read file

do
    if [[ ! ${file} =~ .php$ ]] ;then
        continue
    fi
    if [ ${LOCKING} -eq 1 ] ;then
        echo "Reloading, skipped."
        continue
    fi
    echo "File ${file} has been modified."
    LOCKING=1
    ./bin/laravels reload
    LOCKING=0
done
exit 0