#!/bin/bash
#################################################
# Usage: <script> <PATH-TO-BOOTSTRAP-FOLDER>
# Script will look for cfengine_theme.less file and try to compile it with lessc
# Will write the compiled css file inside the given directory under compiled/css/cfengine_less.css
# incase of error empty css file will be created
#Depends upon inotify  apt-get install inotify-tools
#Depends upon lessc tool ruby 
	#sudo apt-get install rubygems1.8 ruby1.8-dev
	#sudo gem install rubygems-update
	#sudo gem update rubygems
	#sudo gem install less
	#sudo gem install therubyracer

##################################################



# get the current path
CURPATH=`pwd`
BOOTSTRAP_PATH=$1
BOOTSTRAP_LESS_FILE=$1"cfengine_theme.less"

BOOTSTRAP_COMPILED_CSS=$1"compiled/css/cfengine.less.css"
echo "File will be compiled to " $BOOTSTRAP_COMPILED_CSS 
cd $1

inotifywait -mqr --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' \
-e modify $1 | while read date time dir file; do
  ext="${file#*.}"
  if [ "$ext" == "less.new" ]; then
    FILECHANGE=${dir}${file}
    ORIGINALFILE="${file%.*}"	
    # convert absolute path to relative
    FILECHANGEREL=`echo "$FILECHANGE" | sed 's_'$CURPATH'/__'`
    echo "original file name "$ORIGINALFILE	

    echo "At ${time} on ${date}, file $FILECHANGE was changed. Rebuilding."

    # Actual command to execute when CSS or JS file is changed
    touch $BOOTSTRAP_COMPILED_CSS > /dev/null 2>&1 && echo "File $BOOTSTRAP_COMPILED_CSS  created."	
    lessc $BOOTSTRAP_LESS_FILE > $BOOTSTRAP_COMPILED_CSS	  
  fi
done
