#!/usr/bin/env zsh

autoload colors
colors
for COLOR in RED GREEN YELLOW BLUE MAGENTA CYAN BLACK WHITE; do
    eval $COLOR='$fg_no_bold[${(L)COLOR}]'
    eval BOLD_$COLOR='$fg_bold[${(L)COLOR}]'
done
eval RESET='$reset_color'

latestThread=0
relaunchCompilation() {
    while read line; do
        if (( $( print -- $line | grep '.cabal-sandbox' | wc -l) == 0 )); then
            (($latestThread>0)) && \
            (( $(ps x | awk "\$1 == $latestThread" | wc -l)>0 )) && {
                print -- "\n${RED}STOPPED${RESET}"
                kill $latestThread
            }
            print "${BLUE}$line${RESET}"
            { cabal install && \
                ./.cabal-sandbox/bin/test-holy-project } &
            latestThread=$!
        fi
    done
}

echo "First launch" | relaunchCompilation
case $(uname) in
Darwin)
    # On mac OS X, use hobbes (cabal install hobbes)
    # launch a cabal install and cabal test after each
    # small haskell file modification
    {hobbes "*.hs" | relaunchCompilation } &
    hobbes "*.cabal" | relaunchCompilation
    ;;
*)  # On other Unixes
    tmp=$(date +"%s")
    t=$tmp
    while true; do
      tmp=$(( $t - 1 ))
      t=$(date +"%s")
      for fic in {src,test}/**/*.hs(.) *.cabal; do
          # note to use on OS X, use "stat -f %m $checkfile" instead
          modtime=$(stat --printf %Y $fic)
          (( $modtime > $tmp )) && print $fic
      done
      sleep 1
    done | relaunchCompilation
    ;;
esac