#!/bin/sh

#
# Script used for 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_INSTALL_DIR=${DM_INSTALL_DIR:=$DM_ROOT_DIR/..}
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_HOST=${DM_DB_HOST:=localhost}
DM_DB_PORT=${DM_DB_PORT:=11136}
DM_DB_USER=${DM_DB_USER:=dm}
DM_DB_PASSWORD=${DM_DB_PASSWORD:=dm}
DM_DB_POOL=postgresql_${DM_DB_NAME}_DbPool
DM_DATA_SOURCE=${DM_DB_NAME}_DataSource
DM_DOMAIN=domain1

# copy db driver
echo "Copying db driver"
rsync -ar $DM_ROOT_DIR/src/java/DmWebPortal/lib/postgresql-9.3-1102.jdbc41.jar $GLASSFISH_DIR/glassfish/domains/${DM_DOMAIN}/lib/ext

# Check password from file
passwordFile=$DM_INSTALL_DIR/etc/$DM_DB_NAME.db.passwd
if [ -f $passwordFile ]; then
    DM_DB_PASSWORD=`cat $passwordFile`
fi

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

# create JDBC connection pool
echo "Creating JDBC connection pool $DM_DB_POOL"
$ASADMIN_CMD create-jdbc-connection-pool --datasourceclassname org.postgresql.ds.PGSimpleDataSource --restype javax.sql.DataSource --property user=${DM_DB_USER}:password=${DM_DB_PASSWORD}:driverClass="org.postgresql.Driver":portNumber=${DM_DB_PORT}:databaseName=${DM_DB_NAME}:serverName=${DM_DB_HOST}:url="jdbc\:postgresql\://${DM_DB_HOST}\:${DM_DB_PORT}/${DM_DB_NAME}" ${DM_DB_POOL}

# create JDBC resource associated with this connection pool
echo "Creating JDBC resource $DM_DATA_SOURCE"
$ASADMIN_CMD create-jdbc-resource --connectionpoolid ${DM_DB_POOL} ${DM_DATA_SOURCE}

# test the connection settings 
echo "Testing connection"
$ASADMIN_CMD ping-connection-pool $DM_DB_POOL || exit 1

