#! /bin/sh
INSTALLDIR=<msg.RootPath>
# something like /opt/SUNWwbsvr/https-ketu.west.sun.com/config
#  this directory contains the server.xml file
WEBSERVER_CONFIGDIR=<webserverInstancedir>/config
# this is what to add to the classpath
ADDITIONALPATH=$INSTALLDIR/data/WEB-INF/classes

# derive webserver base
WEBSERVER_BASEDIR=`dirname $WEBSERVER_CONFIGDIR`
WEBSERVER_INSTANCE=`basename $WEBSERVER_BASEDIR`
WEBSERVER_BASEDIR=`dirname $WEBSERVER_BASEDIR`

PATH=/bin:/usr/bin:/sbin:/usr/sbin
CP="/usr/bin/cp -p"


##############################################################
#
# line manipulation routine
#

replace_line() {
  file=$1
  match=$2
  new=$3

  $CP $file $file-orig-$$
  sed -e "
/$match/ {
c\\
$new
}" $file > $file-tmp
cp $file-tmp $file
rm -f $file-tmp
}

#
# configure webserver 61
#
configure_webserver_61() {
    echo "Configuring webserver 6.1 ..."
    echo "Modifying ${WEBSERVER_CONFIGDIR}/server.xml file"
    #changing server.xml for classpath

    JVM_CLASSPATH_CLASSES="${ADDITIONALPATH}"
    cd ${WEBSERVER_CONFIGDIR}

    #step1: grep for classpath suffix in server.xml
    file="server.xml"
    classpath=`grep serverclasspath $file`

    matches=`echo $classpath | grep ${JVM_CLASSPATH_CLASSES} | wc -l`
    if [ "$matches" -ne 0 ]
    then
        echo "additional path is already in serverclasspath"
        return
    fi

    #step2: Get the number of tokens in the <JAVA> .. </JAVA>
    var=`echo $classpath | nawk ' { print NF } '`

    #step3: Add our classpath to the existing serverclasspath in server.xml
    count=1
    newline=""
    while [ $count -le $var ] 
    do
        currentToken=`echo $classpath | cut -f$count -d " "`
        classpathToken=`echo $currentToken | grep "serverclasspath"`
        if [ "$classpathToken" != "" ]; then
            classpathToken=`echo $classpathToken | nawk ' BEGIN { FS="=" } { print $2 } ' | cut -f2 -d "\""`
            classpathToken="\"${JVM_CLASSPATH_CLASSES}:$classpathToken\""
            serverclasspath="serverclasspath=$classpathToken"
            newline="$newline $serverclasspath"
        else
            newline="$newline $currentToken"
        fi
        count=`expr $count + 1`
    done
    replace_line "$file" "serverclasspath" "$newline"

}

##############################################################
#
# start main
#

configure_webserver_61

# deploy web application
if [ -f "${WEBSERVER_BASEDIR}/bin/https/httpadmin/bin/wdeploy" ]
then
  echo ${WEBSERVER_BASEDIR}/bin/https/httpadmin/bin/wdeploy deploy -u /commcli -i ${WEBSERVER_INSTANCE} -v ${WEBSERVER_INSTANCE} ${INSTALLDIR}/lib/jars/commcli-server.war -d ${INSTALLDIR}/data
  ${WEBSERVER_BASEDIR}/bin/https/httpadmin/bin/wdeploy deploy -u /commcli -i ${WEBSERVER_INSTANCE} -v ${WEBSERVER_INSTANCE} ${INSTALLDIR}/lib/jars/commcli-server.war -d ${INSTALLDIR}/data
  if [ $? != 0 ]
  then
    $ECHO "Unable to deploy services."
    exit 1
  fi     
fi
