#!/bin/bash

RETVAL=0
dir=`dirname $0`
PATH=$dir:/bin:/sbin:/usr/sbin:/usr/bin:/usr/libexec

PFXDIR=/usr/local/pfx
QBDIR=$PFXDIR/qube
PGSQLDIR=$PFXDIR/pgsql
PGSQL_DATA_DIR=$PGSQLDIR/data

SYSTEMD_DIR='/lib/systemd/system'

uninstall_db() {
	# stop the postgresql DB server
    echo "Stopping DB..."
	su pfx -c "$QBDIR/utils/pgsql/stopdb.sh"

    echo "Disabling postgresql-pfx startup..."

	echo "Stopping and uninstalling postgresql-pfx service..."
	if [ -e $SYSTEMD_DIR/postgresql-pfx.service ]
	then
		# CentOS/RHEL 7+ uses systemd 
		systemctl stop postgresql-pfx.service
		sleep 3
		systemctl disable postgresql-pfx.service
	else
		/sbin/service postgresql-pfx stop
		sleep 3
		/sbin/chkconfig --del postgresql-pfx
	fi
}

uninstall_supervisor() {

    if [ -e $SYSTEMD_DIR//supervisor.service ]
    then
        echo "Shutting down supervisor..."
	systemctl stop supervisor

        echo "Disabling supervisor startup..."
        systemctl disable supervisor
    else
        echo "Shutting down supervisor..."
        $INIT_DIR/supervisor stop
        echo "Disabling supervisor startup..."
        /sbin/chkconfig --del supervisor

        for level in 2 3 4 5;
        do
		/bin/rm -f /etc/rc${level}.d/*supervisor;
        done

        echo "Deleting supervisor..."
        /bin/rm -f $INIT_DIR/supervisor
    fi

    /bin/rm -f /etc/logrotate.d/supervisor

}

if [ -e /etc/rc.d/init.d ]
then
    INIT_DIR='/etc/rc.d/init.d'
elif [ -e /etc/init.d ]
then
    INIT_DIR='/etc/init.d'
fi

echo "Uninstalling supervisor..."
uninstall_supervisor

echo "Uninstalling db..."
uninstall_db

echo "Done!"
exit $RETVAL
