#!/bin/bash
# deploy
#
#{{IS_NOTE
#	Purpose:
#		Deploy
#	Description:
#		It supports tomcat only.
#	History:
#		Thu Jan 26 09:47:39     2006, Created by tomyeh
#}}IS_NOTE
#
#Copyright (C) 2006 Potix Corporation. All Rights Reserved.
#
#{{IS_RIGHT
#	This program is distributed under GPL Version 3.0 in the hope that
#	it will be useful, but WITHOUT ANY WARRANTY.
#}}IS_RIGHT
#
setting=build.setting.local
if [ ! -f $setting ] ; then
	setting=build.setting
fi

tomcat=$(grep '^tomcat' $setting)
tomcat=${tomcat#tomcat=}
if [ "$tomcat" = "" ] ; then
	tomcat=/usr/tomcat
fi
if [ ! -d $tomcat ] ; then
	echo "$tomcat not found"
	echo "Currently only tomcat is supported"
	exit 1
fi

if [ $# == 0 ] ; then
	echo "Usage:"
	echo "  deploy prj1 prj2..."
	exit 0
fi

function cpweb {
	(
		cd $1
		for sub in * ; do
			if [ -f "$sub" ] ; then
				#echo cp -u -p "$sub" $2
				cp -u -p -v "$sub" $2
			elif [ "$sub" != CVS ] && [ "$sub" != .svn ] && [ -d "$sub" ] ; then
				local dstsub=$2/$sub
				if [ ! -d "$dstsub" ] ; then
					mkdir -p "$dstsub"
				fi
				#echo cpweb $(pwd)/$sub $dstsub
				cpweb $sub $dstsub
			fi
		done
	)
}

jar_found=false
for f in $*; do
	f=${f%/}
	if [ -f dist/lib/$f.war ] && [ "$(head -1 $f/format)" = "war" ] ; then
		dst=$(grep '^root' $f/deploy)
		if [ "$dst" = "root" ] ; then
			dst=ROOT
		else
			dst=$f
		fi
		echo "cp dist/lib/$f $tomcat/webapps/$dst"
		cpweb $f/src/archive $tomcat/webapps/$dst
	fi
	if [ -f dist/lib/$f.jar ] || [ -f dist/lib/ext/$f.jar ] ; then
		jar_found=true
	fi
done

if [ "$jar_found" = "true" ] ; then
	if [ -f $setting ] ; then
		service=$(grep '^start.service' $setting)
		service=${service#start.service=}
	fi

	if [ "$service" != "" ] ; then
		if [ "$service" = "startup.sh" ] ; then
			$tomcat/bin/shutdown.sh
		else
			net stop "$service"
		fi
	fi

	for f in $*; do
		f=${f%/}
		if [ -f dist/lib/$f.jar ] ; then
			#echo "cp dist/lib/$f.jar $tomcat/shared/lib"
			chmod 644 dist/lib/$f.jar
			cp -p -u -v -f dist/lib/$f.jar $tomcat/shared/lib
		fi
		if [ -f dist/lib/ext/$f.jar ] ; then
			#echo "cp dist/lib/ext/$f.jar $tomcat/shared/lib"
			chmod 644 dist/lib/ext/$f.jar
			cp -p -u -v -f dist/lib/ext/$f.jar $tomcat/shared/lib
		fi
	done

	if [ "$service" != "" ] ; then
		if [ "$service" = "startup.sh" ] ; then
			$tomcat/bin/startup.sh
		else
			net start "$service"
		fi
	fi
fi
