#!/bin/bash

BASE_DIR="${PWD}/`dirname ${0}`"
BASE_DIR=`readlink -f "$BASE_DIR"`
SOURCE_DIR=`readlink -f "${BASE_DIR}/${1}"`
BUILD_NAME=`basename $1`
BUILD_FILE="${SOURCE_DIR}/.build"
BUILD_DATA="${SOURCE_DIR}/.build_data"
BUILD_DIR=`dirname $SOURCE_DIR`
BUILD_DATA_GENERATED=0

YUI_COMPRESSOR=`which yuicompressor`
BUILD_TYPE="js"

if [ -z $YUI_COMPRESSOR ]; then
    YUI_COMPRESSOR=`which yui-compressor`
    if [ -z $YUI_COMPRESSOR ]; then
	echo "Please install yuicompressor"
	exit 1
    fi
fi

add_file()
{
	 FILES="${FILES} ${SOURCE_DIR}/$1"
}

check_file()
{
    # No build data is stored so return 1 since we can't make any guesses.
    [ ! -e $BUILD_DATA ] && return 1;

    FILE=$1
    LAST_BUILD=`grep $FILE $BUILD_DATA`
    if [ $? == 1 ]; then return 1; fi; 

    CURRENT=`grep $FILE $BUILD_DATA.tmp`

    [ "$CURRENT" != "$LAST_BUILD" ] && return 1

    return 0;	
}

gen_build_data()
{
	for FILE in $FILES; do
		md5sum $FILE >> $BUILD_DATA.tmp
	done;
	BUILD_DATA_GENERATED=1
}

check()
{
	# no build data exists so we can't make guesses
	[ -e $BUILD_DATA ] || return 1
	
	# remove an existing temp build data file
	[ -e $BUILD_DATA.tmp ] && rm $BUILD_DATA.tmp

	# generate new build data
	gen_build_data

	# check files for building
	NEEDS_BUILDING=0
    for FILE in $FILES; do
        check_file $FILE || NEEDS_BUILDING=1
    done;

	# return the result
	return $NEEDS_BUILDING
}

build()
{

	echo "building $BUILD_NAME"

	# generated the unminified version
	cat $FILES > $BUILD_DIR/$BUILD_NAME-debug.js

	# generated the minified version
	$YUI_COMPRESSOR --type=$BUILD_TYPE -o "$BUILD_DIR/$BUILD_NAME.js" \
		$BUILD_DIR/$BUILD_NAME-debug.js
	
	# generate build data incase there hasn't been any
	[ $BUILD_DATA_GENERATED = 1 ] || gen_build_data

	# move new build data to take the place of the old data
	mv $BUILD_DATA.tmp $BUILD_DATA
}

do_exit()
{
    echo $1
    exit $2
}

# check to see if the folders build file exists
[ -e "$BUILD_FILE" ] || do_exit "no build file found" 1

# include the folders build file
. $BUILD_FILE

# check if the build needs to take place
check && do_exit "no changes have been made" 0

build
