#!/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
#
if [ ! -d /usr/tomcat ] ; then
	echo "/usr/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 /usr/tomcat/webapps/$dst"
		cpweb $f/src/archive /usr/tomcat/webapps/$dst
	fi
	if [ -f dist/lib/$f.jad ] ; then
		dstdir=/usr/WTK/apps/$f
		echo "cp $f.jad $dstdir"
		cp -u -p -v dist/lib/$f.jad dist/lib/$f.jar $f/src/archive/META-INF/MANIFEST.MF $dstdir/bin
		cp -urp $f/src/org $dstdir/src
		cp -urp $f/src/archive/icons $dstdir/res
		cp -urp $f/debugv/org $dstdir/classes
	elif [ -f dist/lib/$f.jar ] ; then
		jar_found=true
	fi
done

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

	if [ "$service" != "" ] ; then
		net stop "$service"
	fi

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

	if [ "$service" != "" ] ; then
		net start "$service"
	fi
fi
