#!/bin/sh

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

DM_DB_NAME=dm
DM_DB_HOST=127.0.0.1
DM_DB_PORT=11136
DM_DB_ADMIN_USER=postgres
DM_DB_ADMIN_PASSWORD=


CURRENT_DIR=`pwd`
MY_DIR=`dirname $0` && cd $MY_DIR && MY_DIR=`pwd`
cd $CURRENT_DIR

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 1
fi
. ${DM_ENV_FILE} > /dev/null 

# DM_SUPPORT_DIR should now be defined.
if [ -z "$DM_SUPPORT_DIR" ]; then
    echo "Invalid environment file ${DM_ENV_FILE}: DM_SUPPORT_DIR is not defined."
    exit 1
fi
PG_DIR=$DM_OPT_DIR/postgresql/$DM_HOST_ARCH
PG_CONTROL_SCRIPT=$DM_ROOT_DIR/etc/init.d/dm-postgresql
PG_DATA_DIR=$PG_DIR/data
PG_HBA_CONF=$PG_DATA_DIR/pg_hba.conf
DM_RUN_DIR=${DM_INSTALL_DIR}/var/run
DB_LOCK_FILE=${DM_RUN_DIR}/${DM_DB_NAME}.db.lock

# Use first argument as db name, if provided
if [ ! -z "$1" ]; then
    DM_DB_NAME=$1
fi
DM_DB_USER=$DM_DB_NAME
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

execute() {
    msg="$@"
    if [ ! -z "$DM_DB_ADMIN_PASSWORD" ]; then
        sedCmd="s?$DM_DB_ADMIN_PASSWORD?\\*\\*\\*\\*\\*\\*?g"
        echo "Executing: $@" | sed -e $sedCmd
    else
        echo "Executing: $@"
    fi
    eval "$@"
}

destroyDb() {
    echo "Destroying database $DM_DB_NAME (connecting to db using $DM_DB_ADMIN_USER admin account)"
    ${PG_DIR}/bin/dropdb -U $DM_DB_ADMIN_USER -h $DM_DB_HOST -p $DM_DB_PORT $DM_DB_NAME || return 1
    rm -f $DB_LOCK_FILE 
    echo "Database $DM_DB_NAME destroyed"
}

destroyDbUser() {
    echo "Dropping user $DM_DB_USER (connecting to db using $DM_DB_ADMIN_USER admin account)"
    _dbUser=$1
    shift 1
    _destroyFlags=$@

    # destroy user
    ${PG_DIR}/bin/dropuser -U $DM_DB_ADMIN_USER -h $DM_DB_HOST -p $DM_DB_PORT $_destroyFlags $_dbUser || return 1
    echo "User $DM_DB_USER dropped"
}

# Check for failed earlier attempt
if [ -f $PG_HBA_CONF.orig ]; then
    echo "File $PG_HBA_CONF.orig exists, refusing to proceed."
    exit 1
fi

# Check lock file
if [ ! -f $DB_LOCK_FILE ]; then
    echo "Database $DM_DB_NAME is not found."
    exit 1
fi
read -p "Destroy DB $DM_DB_NAME [y/N]? " proceedFlag
if [ "$proceedFlag" != "y" ]; then
    echo "Database $DM_DB_NAME was not destroyed."
    exit 1
fi

# Destroy db
destroyDb || exit 1

# Destroy db user
destroyDbUser $DM_DB_USER || exit 1

