#!/bin/sh
#

BASE=`basename $0`

THE_CMD=$1
DEPLOY_OP=deploy
UNDEPLOY_OP=undeploy

INSTALLDIR=<msg.RootPath>
URIPATH=<commcli.Uri>
MODULE_NAME=<commcli.ApplicationModuleName>
DEPLOY_DIR=<commcli.ApplicationDeployDir>

APP_SERVER_INSTALL_DIR=<commcli.AppServerInstallDir>
APP_SERVER_DOMAIN_DIR=<commcli.AppServerDomainDir>
APP_SERVER_DOC_ROOT_DIR=<commcli.AppServerDocRootDir>
APP_SERVER_INSTANCE_NAME=<commcli.AppServerInstanceName>
APP_SERVER_VS_ID=<commcli.AppServerVirtualServerID>

APP_SERVER_ADMIN_HOST=<commcli.AppServerAdminHost>
APP_SERVER_ADMIN_PORT=<commcli.AppServerAdminPort>
APP_SERVER_ADMIN_USER_ID=<commcli.AppServerAdminUserID>
APP_SERVER_ADMIN_USER_PSWD=<commcli.AppServerAdminUserPswd>
APP_SERVER_ADMIN_USER_PASSWORD_FILE=<commcli.AppServerAdminUserPasswordFile>
APP_SERVER_IS_SECURE_ADMIN_INSTANCE=<commcli.AppServerIsSecureAdminInstance>

# this is what to add to the classpath
ADDITIONALPATH=$INSTALLDIR/data/WEB-INF/classes

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

##############################################################
#
# 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 application server 7.x
#
configure_appserver() {
    echo "Configuring application server 7.x ..."
    echo "Modifying ${AS_CONFIG_DIR}/server.xml file"
    #changing server.xml for classpath-suffix

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

    #step1: grep for classpath suffix in server.xml
    file="server.xml"
    classpath=`grep classpath-suffix $file | ${AWK} 'NR==1'`
    matches=`echo $classpath | grep ${JVM_CLASSPATH_CLASSES} | wc -l`
    if [ "$matches" -ne 0 ]
    then
        echo "additional path is already in classpath-suffix"
        return
    fi

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

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

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

# Check the option
#
if [ "$THE_CMD" = "" ]
then
  echo "$BASE: Usage ERROR: No option specified."
  echo "Usage: $BASE <option>"
  echo "  where valid values for <option> are '$DEPLOY_OP' or '$UNDEPLOY_OP'"
  exit 1
elif [ "$THE_CMD" != "$DEPLOY_OP"  -a  "$THE_CMD" != "$UNDEPLOY_OP" ]
then
  echo "$BASE: Usage ERROR: INVALID option '$THE_CMD' specified."
  echo "Usage: $BASE <option>"
  echo "  where valid values for <option> are '$DEPLOY_OP' or '$UNDEPLOY_OP'"
  exit 1
fi

# Add secure option id enabled
#
SECURE_OPTION=" "
if [ "true" = "${APP_SERVER_IS_SECURE_ADMIN_INSTANCE}" ]
then
  SECURE_OPTION=" --secure"
fi

# Perform the command
#
if [ -f "${APP_SERVER_INSTALL_DIR}/bin/asadmin" ]
then
  if [ "$THE_CMD" = "$UNDEPLOY_OP" ]
  then
      echo "ERROR: Undeploying is not supported...."
      exit 1
  elif [ "$THE_CMD" = "$DEPLOY_OP" ]
  then
     AS_INST_DIR="${APP_SERVER_DOMAIN_DIR}/${APP_SERVER_INSTANCE_NAME}"
     if [ -d "${AS_INST_DIR}" ]
     then
       AS_CONFIG_DIR="${AS_INST_DIR}/config"
       if [ ! -d "${AS_CONFIG_DIR}" ]
       then
         echo "ERROR: Application Server Instance Config Directory does not exits: ${AS_CONFIG_DIR}: No such directory...."
         exit 1
       fi

       AS_CONFIG_BACK_UP_DIR="${AS_CONFIG_DIR}/.DA_`date +%Y%m%d%H%M%S`/"

       echo /bin/mkdir -p "${AS_CONFIG_BACK_UP_DIR}"
       /bin/mkdir -p "${AS_CONFIG_BACK_UP_DIR}"

       if [ $? != 0 ]
       then
         echo "ERROR: Cannot create config backup directory ${AS_CONFIG_BACK_UP_DIR} ...."
         exit 1
       fi

       echo ""
       echo "Taking config backup into directory: ${AS_CONFIG_BACK_UP_DIR} ...."

       echo ""
       echo /bin/chmod 700 "${AS_CONFIG_BACK_UP_DIR}" 
       /bin/chmod 700 "${AS_CONFIG_BACK_UP_DIR}" 

       echo ""
       echo /bin/cp -r "${AS_CONFIG_DIR}/server.xml ${AS_CONFIG_BACK_UP_DIR}"
       /bin/cp -r ${AS_CONFIG_DIR}/server.xml ${AS_CONFIG_BACK_UP_DIR}

       if [ $? != 0 ]
       then
         echo "ERROR: Could not backup ${AS_CONFIG_DIR}/server.xml ..."
       fi

       echo ""
       echo /bin/cp -r "${AS_CONFIG_DIR}/server.policy ${AS_CONFIG_BACK_UP_DIR}"
       /bin/cp -r ${AS_CONFIG_DIR}/server.policy ${AS_CONFIG_BACK_UP_DIR}

       if [ $? != 0 ]
       then
         echo "ERROR: Could not backup ${AS_CONFIG_DIR}/server.policy ..."
       fi
     else
       echo "ERROR: Application Server Instance Directory does not exits: ${AS_INST_DIR}: No such directory...."
       exit 1
     fi

     echo ""
     echo ""

     echo ${APP_SERVER_INSTALL_DIR}/bin/asadmin deploydir --user "${APP_SERVER_ADMIN_USER_ID}" --password xxxxxxx ${SECURE_OPTION} --host "${APP_SERVER_ADMIN_HOST}" --port "${APP_SERVER_ADMIN_PORT}" --instance "${APP_SERVER_INSTANCE_NAME}" --virtualservers "${APP_SERVER_VS_ID}" --contextroot ${URIPATH} --force=true --type web --name "${MODULE_NAME}" ${DEPLOY_DIR}
     ${APP_SERVER_INSTALL_DIR}/bin/asadmin deploydir --user "${APP_SERVER_ADMIN_USER_ID}" --password "${APP_SERVER_ADMIN_USER_PSWD}" ${SECURE_OPTION} --host "${APP_SERVER_ADMIN_HOST}" --port "${APP_SERVER_ADMIN_PORT}" --instance "${APP_SERVER_INSTANCE_NAME}" --virtualservers "${APP_SERVER_VS_ID}" --contextroot ${URIPATH} --force=true --type web --name "${MODULE_NAME}" ${DEPLOY_DIR}

     if [ $? = 0 ]
     then
       echo "Deployed the application successfully...."
     else
       echo "ERROR: Failed deploying the application...."
       exit 1
     fi

     # Add classpath to commcli-client.jar and jdapi.jar
     #
     configure_appserver

     echo ""
     echo ""

     if [ -d "${AS_INST_DIR}" ]
     then
        AS_CONFIG_DIR="${AS_INST_DIR}/config"
        SERVER_POLICY_FILE="${AS_CONFIG_DIR}/server.policy"

        if [ -f "${SERVER_POLICY_FILE}" ]
        then
cat << END_OF_FILE >> ${SERVER_POLICY_FILE}

// Start: Delegated Administrator related additions
grant {
        permission java.util.PropertyPermission "user.language", "write";
};
// end: Delegated Administrator related additions

END_OF_FILE
           echo "INFO: Successfully configured server.policy file: ${SERVER_POLICY_FILE}...."  
        else
           echo ""
           echo "ERROR: Could not configure server.policy."
           echo "  Reason: Could not locate ${SERVER_POLICY_FILE}: No such file exists...."
           echo "Please do it manually...."
        fi
     else
       echo ""
       echo "ERROR: Could not configure server.policy."
       echo "  Reason: Application Server Instance Directory does not exits: ${AS_INST_DIR}: No such directory...."
       echo "Please do it manually...."
     fi

     echo ""
     echo ""

     echo ${APP_SERVER_INSTALL_DIR}/bin/asadmin reconfig --user "${APP_SERVER_ADMIN_USER_ID}" --password xxxxxxx ${SECURE_OPTION} --host "${APP_SERVER_ADMIN_HOST}" --port "${APP_SERVER_ADMIN_PORT}" --keepmanualchanges=true "${APP_SERVER_INSTANCE_NAME}"
     ${APP_SERVER_INSTALL_DIR}/bin/asadmin reconfig --user "${APP_SERVER_ADMIN_USER_ID}" --password "${APP_SERVER_ADMIN_USER_PSWD}" ${SECURE_OPTION} --host "${APP_SERVER_ADMIN_HOST}" --port "${APP_SERVER_ADMIN_PORT}" --keepmanualchanges=true "${APP_SERVER_INSTANCE_NAME}"

     if [ $? = 0 ]
     then
       echo "Reconfigured the application server instance successfully...."
     else
       echo "ERROR: Failed Reconfiguring the application server...."
       exit 1
     fi

     echo ""
     echo ""

     echo ${APP_SERVER_INSTALL_DIR}/bin/asadmin get --user "${APP_SERVER_ADMIN_USER_ID}" --password xxxxxxx ${SECURE_OPTION} --host "${APP_SERVER_ADMIN_HOST}" --port "${APP_SERVER_ADMIN_PORT}" "${APP_SERVER_INSTANCE_NAME}.web-module.${MODULE_NAME}.*"
     ${APP_SERVER_INSTALL_DIR}/bin/asadmin get --user "${APP_SERVER_ADMIN_USER_ID}" --password "${APP_SERVER_ADMIN_USER_PSWD}" ${SECURE_OPTION} --host "${APP_SERVER_ADMIN_HOST}" --port "${APP_SERVER_ADMIN_PORT}" "${APP_SERVER_INSTANCE_NAME}.web-module.${MODULE_NAME}.*"

     if [ $? != 0 ]
     then
       echo "ERROR: Failed Getting the module attributes...."
     fi
  fi
else
  echo "ERROR: Unable to locate the asadmin command: ${APP_SERVER_INSTALL_DIR}/bin/asadmin"
  echo "$BASE: ERROR performing command '$THE_CMD'"
  exit 1
fi

exit 0
