#!/bin/sh

#
# Script used for destroying all DM databases
#
# Usage:
#
# $0 
#

DM_DB_NAME=dm
DM_DB_USER=dm
DM_DB_PASSWORD=dm
DM_DB_HOST=127.0.0.1
DM_DB_PORT=11136
DM_DB_ADMIN_USER=postgres
DM_DB_ADMIN_HOSTS="127.0.0.1 bluegill1.aps.anl.gov visa%.aps.anl.gov"
DM_DB_ADMIN_PASSWORD=
DM_DB_CHARACTER_SET=utf8


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_SQL_DIR=$DM_ROOT_DIR/db
DM_RUN_DIR=$DM_ROOT_DIR/var/run
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_SUPPORT_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
DB_CREATE_SCRIPT=${DM_ROOT_DIR}/db/create_${DM_DB_NAME}_db.sql

# Ask user to verify this action
cd $DM_RUN_DIR
lockFileList=`ls -c1 *.db.lock 2> /dev/null`

if [ -z $lockFileList ]; then
    echo "There are no active databases"
else
    dbNamelist=""
    for lockFile in $lockFileList; do
        dbName=`echo $lockFile | cut -f1 -d'.'`
        dbNameList="$dbNameList $dbName"
    done
    echo "Found active databases: $dbNameList"
    read -p "Proceed [y/N]? " proceedFlag
    if [ "$proceedFlag" != "y" ]; then
        echo "Active databases were not destroyed."
        exit 1
    fi
fi

# Stop db.
$PG_CONTROL_SCRIPT stop

# Remove db data directory
echo "Removing database directory"
rm -rf $PG_DATA_DIR

# Remove lock files.
if [ ! -z "$lockFileList" ]; then
    echo "Removing lock files"
    rm -f $lockFileList
fi

echo "Cleanup done"
echo


