#! /bin/sh
# $Id: //NW/dev/nw_19_8/mcui/monitoring/postgresdb/nwuidb.sh#1 $ Copyright (c) 2021 EMC Corporation
#
#
# Copyright (c) 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# This software contains the intellectual property of Dell Inc.
# or is licensed to Dell Inc. from third parties. Use of this
# software and the intellectual property contained therein is
# expressly limited to the terms and conditions of the License
# Agreement under which it is provided by or on behalf of Dell
# Inc. or its subsidiaries.
#
getPostgresPid()
{
    pgrep -U ${POSTGRESDB_USER} -f "postgres -D" > /dev/null
    if [ $? -eq 0 ]; then
        pid=`pgrep -U ${POSTGRESDB_USER} -f "postgres -D"` > /dev/null
    fi
    return $pid
}

start_db()
{
echo >&2 "Starting NWUI Database (Postgres DB)... "

if [ -n "$postgresdb_pid" ]; then
    echo "ERROR: Postgres DB is already running! pid: $postgresdb_pid" >&2
    retval=1;
else
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${POSTGRESDB_LIB}
    #starting the db
    $POSTGRES -D $POSTGRESDB_DATA &> $POSTGRESDB_LOG
    retval=$?
    if [ ${retval} -eq 0 ]; then
        echo >&2 "Postgres DB started Successfully"
    else
        echo >&2 "ERROR: Could not start Postgres DB !!!, error: $retval"
    fi
fi
return $retval
}

stop_db()
{
echo >&2 $"Stopping NWUI Database (Postgres DB): "

if ! [ -n "$postgresdb_pid" ]; then
    echo "ERROR: Postgres DB is not running! " >&2
    exit 1
fi

#Stop the db
su -m $POSTGRESDB_USER -c "${PG_CTL} --pgdata=${POSTGRESDB_DATA} stop"
retval=$?
if [ ${retval} -eq 0 ]; then
    echo >&2 "Postgres DB server stopped Successfully"
else
    echo >&2 "ERROR: Could not stop Postgres DB server !!!, error: $retval"
fi
return $retval
}


#
#main
#
nwuihome=`rpm -q --qf "%{INSTPREFIXES}\n" lgtonwui 2> /dev/null`
nwuiservhome=`rpm -q --qf "%{INSTPREFIXES}\n" lgtonwuiserv 2> /dev/null`
if [ "$nwuihome" == "package lgtonwui is not installed" ]; then
    MCUI_HOME=$nwuiservhome
else
    MCUI_HOME=$nwuihome
fi
MONITORING_HOME="${MCUI_HOME}/monitoring"
POSTGRESDB_HOME="${MONITORING_HOME}/postgres/12"
MONITORING_BASE="/nsr/nwui/monitoring"
POSTGRESDB_RUNNING_DIR="${MONITORING_BASE}/nwuidb"
POSTGRESDB_BIN="${POSTGRESDB_HOME}/bin"
POSTGRESDB_LIB="${POSTGRESDB_HOME}/lib"
POSTGRESDB_DATA="${POSTGRESDB_RUNNING_DIR}/pgdata"
POSTGRESDB_LOG="${POSTGRESDB_RUNNING_DIR}/logs/nwuidb.log"
INITDB="${POSTGRESDB_BIN}/initdb"
PG_CTL="${POSTGRESDB_BIN}/pg_ctl"
POSTGRES="${POSTGRESDB_BIN}/postgres"
POSTGRESDB_USER=nsrnwui
POSTGRESDB_GROUP=nsrnwui

# Getting postgresdb PID
postgresdb_pid=`getPostgresPid`

retval=0
case $1 in
    start)
        start_db
        retval=$?
        ;;
    stop)
        stop_db
        retval=$?
        ;;
    *)
    echo "usage: `basename $0` {start|stop}"
    retval=1
    ;;
esac
exit $retval

