#!/bin/sh

#
# Script used for undeploying DM webapp
# Deployment configuration can be set in etc/$DM_DB_NAME.deploy.conf file
#
# Usage:
#
# $0 [DM_DB_NAME]
#

MY_DIR=`dirname $0` && cd $MY_DIR && MY_DIR=`pwd`
if [ -z "${DM_ROOT_DIR}" ]; then
    DM_ROOT_DIR=$MY_DIR/..
fi
DM_ENV_FILE=${DM_ROOT_DIR}/setup.sh
if [ ! -f ${DM_ENV_FILE} ]; then
    echo "Environment file ${DM_ENV_FILE} does not exist." 
    exit 2
fi
. ${DM_ENV_FILE} > /dev/null

# Use first argument as db name, if provided
DM_DB_NAME=${DM_DB_NAME:=dm}
if [ ! -z "$1" ]; then
    DM_DB_NAME=$1
fi
echo "Using DB name: $DM_DB_NAME"

# Look for deployment file in etc directory, and use it to override
# default entries
deployConfigFile=$DM_ROOT_DIR/etc/${DM_DB_NAME}.deploy.conf
if [ -f $deployConfigFile ]; then
    echo "Using deployment config file: $deployConfigFile"
    . $deployConfigFile
else
    echo "Deployment config file $deployConfigFile not found, using defaults"
fi

DM_HOST_ARCH=`uname | tr [A-Z] [a-z]`-`uname -m`
DM_CONTEXT_ROOT=${DM_CONTEXT_ROOT:=dm}
JAVA_HOME=$DM_OPT_DIR/java/$DM_HOST_ARCH
GLASSFISH_DIR=$DM_OPT_DIR/glassfish
DM_DEPLOY_DIR=$GLASSFISH_DIR/glassfish/domains/domain1/autodeploy
DM_APP_DIR=$GLASSFISH_DIR/glassfish/domains/domain1/applications/$DM_CONTEXT_ROOT
DM_DIST_DIR=$DM_ROOT_DIR/src/java/DmWebPortal/dist
DM_WAR_FILE=$DM_CONTEXT_ROOT.war

export AS_JAVA=$JAVA_HOME
ASADMIN_CMD=$GLASSFISH_DIR/bin/asadmin

# remove war file from autodeploy directory
echo "Removing war file $DM_DEPLOY_DIR/$DM_WAR_FILE"
rm -f $DM_DEPLOY_DIR/${DM_WAR_FILE}*

# remove war file from autodeploy directory
if [ -d $DM_APP_DIR ]; then
    echo "Removing application directory $DM_APP_DIR"
    rm -rf $DM_APP_DIR
else
    echo "Application directory $DM_APP_DIR not found"
fi

# restart server
echo "Restarting glassfish"
$ASADMIN_CMD stop-domain ${DM_DOMAIN}
$ASADMIN_CMD start-domain ${DM_DOMAIN}




