#!/bin/sh

#
# Script used for un-configuring 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`
GLASSFISH_DIR=$DM_SUPPORT_DIR/glassfish/$DM_HOST_ARCH
JAVA_HOME=$DM_SUPPORT_DIR/java/$DM_HOST_ARCH

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

DM_DB_POOL=postgresql_${DM_DB_NAME}_DbPool
DM_DATA_SOURCE=${DM_DB_NAME}_DataSource
DM_DOMAIN=domain1

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

# delete JDBC resource associated with this connection pool
echo "Deleting JDBC resource $DM_DATA_SOURCE"
$ASADMIN_CMD delete-jdbc-resource ${DM_DATA_SOURCE}

# delete JDBC connection pool
echo "Deleting JDBC connection pool $DM_DB_POOL"
$ASADMIN_CMD delete-jdbc-connection-pool ${DM_DB_POOL}


