#!/bin/sh
#Javascript Library Builder
#
#Copyright (C) 2009 Bernhard Häussner <bxt@die-optimisten.net>
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License 
#as publishedby the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful, 
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, see <http://www.gnu.org/licenses/>.


#set defaults
licence=licence.txt
override=0

#parse options
while getopts ho:l:c o
do	case "$o" in
	h)	echo
		echo "Javascript Library Builder by Bernhard Häussner"
		echo "Usage: $0 [-c] [-l licencefilename] -o builddir sourcedirs"
		echo "Puts files together to minifyed js-files. "
		echo
		echo "DESCRIPTION"
		echo "  All files in folders in builddir will be combined to minifyed"
		echo "  js files with the name of the folder. You can optionally append"
		echo "  a licence file to those minifyed files. The combined files are "
		echo "  written to builddir"
		echo
		echo "OPTIONS"
		echo "  -c   Delete builddir contents (will override anyway)"
		echo "  -o   The builddir"
		echo "  -l   Name of an optional prepended (Non shortened) Licence file"
		echo
		echo "REQUIRES"
		echo "  jsmin - The JavaScript Minifier"
		echo "       http://www.crockford.com/javascript/jsmin.html"
		echo 
		exit 1;;
	l)	licence="$OPTARG";;
	o)	builddir="$OPTARG";;
	c)	override=1;;
	[?])	print >&2 "Usage: $0 [-k] [-b builddir] [-s sourcedir] [-l licencefilename]"
		exit 1;;
	esac
done
shift $(($OPTIND - 1))
if [ "$1" = "" ]; then
	echo "Error: Please specify sourcedir. Use $0 -h for help. "
	exit 1
fi
srcdirs=$*
if [ "$builddir" = "" ]; then
	echo "Error: Pease specify builddir. Use $0 -h for help. "
	exit 1
fi


#clear builddir
if [ $override -eq 1 ]; then
	if [ -d "$builddir" ]; then
		echo " Cleaning build location $builddir..."
		rm -rv "$builddir"
	fi
fi

#make sure builddir exists
if [ ! -d "$builddir" ]; then
	echo " Creating build loation $builddir"
	mkdir "$builddir"
fi

#main
echo
echo "Starting build. "
echo 
for dir in $srcdirs; do
	dirn=`basename $dir`
	echo " Combining $dir to $builddir/$dirn.js..."
	for file in $dir/*.js; do 
		echo "   Appending $file"
		cat "$file" >> "$builddir/$dirn.js"
		echo >> "$builddir/$dirn.js"
	done
	echo " Minifying $builddir/$dirn.js..."
	jsmin <"$builddir/$dirn.js" > "$builddir/$dirn.min.js"
	rm "$builddir/$dirn.js"
	if [ -s $dir/$licence ]; then 
		 echo " Prepending Licence $dir/$licence"
		 cat $dir/$licence $builddir/$dirn.min.js > /tmp/~libbuildtmp
		 mv /tmp/~libbuildtmp $builddir/$dirn.min.js
	fi
	echo
done
echo
echo "Build completed to $builddir"


