#!/bin/sh

# EnterpriseDB cluster shutdown script
#
# This script will stop clusters listed the /etc/edbtab file
# that have a 'Y' indicating that the cluster should be stopped at
# system shutdown.
# This script is meant to be run at system shutdown 
# (called by /etc/init.d/edb_autostart) but can be run manually.
# If you choose to run this script manually, it will attemp to stop all
# clusters with a 'Y' unless you provide a data directory as an argument:
# i.e ./edbstop /opt/PostgresPlus/9.3AS/data, in which case, only that
# cluster will be stopped.

stopAll ()
{
    # Retrieve all entries from edbtab
    for ENTRY in `cat /etc/edbtab | grep -v '^[ \t]*\#' | egrep -v ':[nN][ \t]*'`
    do
        EDB_HOME=`echo $ENTRY | awk -F: '{print $1}'`
        PGDATA=`echo $ENTRY | awk -F: '{print $2}'`
        printf "Stopping ${EDB_HOME} (${PGDATA})...\n"
        $EDB_HOME/bin/pg_ctl -D $PGDATA -w -m immediate stop
    done
}

stopOne ()
{
    PGDATA=$1

    # Retrieve entry from edbtab
    ENTRY=`cat /etc/edbtab | grep "${PGDATA}"`
    if [ -z $ENTRY ]; then
        printf "Entry could not be found!\n"
        exit 1
    fi

    # Extract components
    EDB_HOME=`echo $ENTRY | awk -F: '{print $1}'`
    PGDATA=`echo $ENTRY | awk -F: '{print $2}'`

    printf "Stopping ${EDB_HOME} (${PGDATA})...\n"
    $EDB_HOME/bin/pg_ctl -D $PGDATA -w -m immediate stop
}

main ()
{
    if [ -z "$1" ]; then
        stopAll
    else
        stopOne $1
    fi
}

main $*
