#!/bin/sh

#
# Script used for undeploying DM PROC web service
# 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}
DM_INSTALL_DIR=${DM_INSTALL_DIR:=$DM_ROOT_DIR/..}
DM_ETC_DIR=${DM_INSTALL_DIR}/etc
DM_SSL_DIR=${DM_ETC_DIR}/ssl
DM_CA_DIR=${DM_ETC_DIR}/CA
DM_CA_CERT_FILE=${DM_SSL_DIR}/dm-ca-cert.pem
DM_WEB_SERVICE_DAEMON=daq-web-service
DM_WEB_SERVICE_CERT_FILE=${DM_SSL_DIR}/$DM_WEB_SERVICE_DAEMON.$DM_DB_NAME.crt
DM_WEB_SERVICE_KEY_FILE=${DM_SSL_DIR}/$DM_WEB_SERVICE_DAEMON.$DM_DB_NAME.key
DM_WEB_SERVICE_CONFIG_FILE=${DM_ETC_DIR}/$DM_WEB_SERVICE_DAEMON.$DM_DB_NAME.conf
DM_WEB_SERVICE_LOG_FILE=${DM_INSTALL_DIR}/var/log/$DM_WEB_SERVICE_DAEMON.$DM_DB_NAME.log
DM_WEB_SERVICE_INIT_CMD=${DM_ROOT_DIR}/etc/init.d/dm-$DM_WEB_SERVICE_DAEMON
DM_DB_PASSWORD_FILE=${DM_ETC_DIR}/${DM_DB_NAME}.db.passwd

echo "DM install directory: $DM_INSTALL_DIR"

echo "Stopping web service for $DM_DB_NAME"
$DM_WEB_SERVICE_INIT_CMD stop $DM_DB_NAME

rm -f $DM_WEB_SERVICE_CONFIG_FILE
rm -f $DM_DB_PASSWORD_FILE
echo "Done undeploying web service for $DM_DB_NAME"
