#!/bin/sh

# Function: _create_postgres_systemd_service
# Purpose : Create the postgres systemd service unit file
# Return  : 0 = Success  1 = An Error Occured
_create_postgres_systemd_service() {

cat > $POSTGRES_SERVICE_UNIT << EOF
# Author: WatchGuard Technologies, Inc
# Description: Provides the builtin PostgreSQL database for WatchGuard Servers

[Unit]
Description=Watchguard PostgreSQL Service
ConditionPathExists=/var/opt/watchguard/dimension/data/db/postgresql.conf
RequiresMountsFor=/var/opt/watchguard/dimension/data
After=local-fs.target
Before=wsserver.service wlogserver.service

[Service]
User=wgadmin
EnvironmentFile=/etc/opt/watchguard/dimension/postgres/postgres.ini
Type=forking
ExecStartPre=-/opt/watchguard/dimension/bin/python /opt/watchguard/dimension/lib/python2.7/site-packages/wg_pg/generator.pyc
ExecStart=-/opt/watchguard/dimension/bin/pg_ctl start -D \$data_directory
ExecStop=-/opt/watchguard/dimension/bin/pg_ctl stop -m fast -D \$data_directory
ExecReload=-/opt/watchguard/dimension/bin/pg_ctl reload -D \$data_directory

[Install]
WantedBy=multi-user.target
EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

return $SUCCESS
}

# Function: _create_postgres_upstart_service
# Purpose : Create the postgress  upstart configuration file
# Return  : 0 = Success  1 = An Error Occured
_create_postgres_upstart_service() {

cat > $POSTGRES_UPSTART_CONF << EOF
description "$DESC"
 
start on runlevel [235]
stop on runlevel [016]

respawn
respawn limit 10 90

pre-start script
PATH="$PATH"
MB=$MB
EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

cat >> $POSTGRES_UPSTART_CONF << "EOF"

/opt/watchguard/dimension/bin/python /opt/watchguard/dimension/lib/python2.7/site-packages/wg_pg/generator.pyc
end script
EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

cat >> $POSTGRES_UPSTART_CONF << EOF

script
TRUE=$TRUE
FALSE=$FALSE
EXTERNAL_DB=$TRUE
POSTGRES_DB_DIR=""
DB_INI_CONF_FILE="$DB_INI_CONF_FILE"
POSTGRES_START_CMD="$POSTGRES_START_CMD"
POSTGRES_CTL_CMD="$POSTGRES_CTL_CMD"
ADMIN="$ADMIN"
PATH="$PATH"
EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

cat >> $POSTGRES_UPSTART_CONF << "EOF"

EXTERNAL_DB=1
POSTGRES_CTL_CMD=""

if [ -r $DB_INI_CONF_FILE ]; then
     EXTERNAL_DB=$(grep "^external_db\>" $DB_INI_CONF_FILE 2> /dev/null  | head -1 | awk -F"=" '{print $2}' | sed -e 's/^ *//' -e 's/ *$//')
     if [ ${#EXTERNAL_DB} -gt 0 ] && [ $EXTERNAL_DB -eq $FALSE ]; then
         POSTGRES_DB_DIR=$(grep "^data_directory\>" $DB_INI_CONF_FILE 2> /dev/null  | head -1 | awk -F"=" '{print $2}' | sed -e 's/^ *//' -e 's/ *$//')
         if [ ${#POSTGRES_DB_DIR} -le 0 ] || [ ! -f "${POSTGRES_DB_DIR}/postgresql.conf" ]; then
             EXTERNAL_DB=1
             POSTGRES_CTL_CMD=""
         fi
     fi
fi


if [ $EXTERNAL_DB -eq $FALSE ] && [ -x $POSTGRES_CTL_CMD ]; then
    exec su -c "$POSTGRES_START_CMD -D $POSTGRES_DB_DIR" $ADMIN
fi
end script
EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

chmod 644 $POSTGRES_UPSTART_CONF 2> /dev/null > /dev/null
# Check the chmod return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

return $SUCCESS
}

# Function: _is_systemd_installed
# Purpose : Check if systemd and systemd-sysv packages are installed
# Return  : 0 = systemd and systemd-sysv are not installed  1 = systemd and systemd-sysv are installed
_is_systemd_installed() {

rc=0
/usr/bin/dpkg -s systemd > /dev/null 2>&1 || rc=$?
if [ $rc -ne 0 ]; then
    return $FALSE
fi
rc=0
/usr/bin/dpkg -s systemd-sysv > /dev/null 2>&1 || rc=$?
if [ $rc -ne 0 ]; then
    return $FALSE
fi

return $TRUE
}

# Function: _is_upstart_installed
# Purpose : Check if upstart executables and /etc/init directory are located
# Return  : 0 = Upstart executables are not installed  1 = Upstart executbales are installed
_is_upstart_installed() {

if [ -x "/sbin/status" ] && [ -x "/sbin/start" ] &&
   [ -x "/sbin/stop" ] && [ -x "/sbin/reload" ] &&
   [ -d "/etc/init" ]; then
       return $TRUE
fi

return $FALSE
}

# Function: _create_postgres_initd_service
# Purpose : Create the postgress initd service
# Return  : 0 = Success   1 = An Error Occured
_create_postgres_initd_service() {
	
cat > $POSTGRES_INITD_SCRIPT << "EOF"
#!/bin/sh

# Author: WatchGuard Technologies, Inc
# Description "This shell script will start, stop, reload, restart, and obtain a status for the WG Postgres Service"
EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

# Needed for Red Hat and its descendants
if [ -x $CHKCONFIG_CMD ]; then
    cat >> $POSTGRES_INITD_SCRIPT << "EOF"

# chkconfig: 235 99 99
EOF

# Check the cat return status
    if [ $? -ne $SUCCESS ]; then
        return $ERROR
    fi
fi

# Needed for Debian to avoid LSB warnings
if [ -x $UPDATERC_CMD ]; then
    cat >> $POSTGRES_INITD_SCRIPT << "EOF"

### BEGIN INIT INFO
# Provides:          wg_pg_service
# Required-Start:    $network $local_fs $syslog
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: $DESC
### END INIT INFO
EOF

# Check the cat return status
    if [ $? -ne $SUCCESS ]; then
        return $ERROR
    fi
fi

# Special case, no quotes around EOF
cat >> $POSTGRES_INITD_SCRIPT << EOF

DESC="$DESC"
NAME="$NAME"

SERVICENAME="$SERVICENAME"
POSTGRES_INITD_SCRIPT="$POSTGRES_INITD_SCRIPT"

ADMIN="$ADMIN"
POSTGRES_CTL_CMD="$POSTGRES_CTL_CMD"
POSTGRES_START_CMD="$POSTGRES_START_CMD"
POSTGRES_STOP_CMD="$POSTGRES_STOP_CMD"
POSTGRES_STATUS_CMD="$POSTGRES_STATUS_CMD"
POSTGRES_RELOAD_CMD="$POSTGRES_RELOAD_CMD"
POSTGRES_DB_DIR="$POSTGRES_DB_DIR"

DB_INI_CONF_FILE="$DB_INI_CONF_FILE"

PATH="$PATH"
MB=$MB              # Megabytes of memory for Postgres DB shared memory    

SUCCESS=$SUCCESS
ERROR=$ERROR
FALSE=$FALSE
TRUE=$TRUE

EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

cat >> $POSTGRES_INITD_SCRIPT << "EOF"

#
# Function that reads a PID from a file and checks if the PID is currently running
# Return one of the following values ( PID_NOT_FOUND or PID_FOUND )
#

PID_NOT_FOUND=0     # PID is not running on the system
PID_FOUND=1         # PID is running on the system
PERMISSION_DENIED=2 # Unable to execute the pg_ctl status command

found_processid() {
ADMIN_UID=`id -u $ADMIN`
CURRENT_USER_UID=`id -u`

if [ $ADMIN_UID -eq $CURRENT_USER_UID ]; then
    pid=$($POSTGRES_STATUS_CMD $POSTGRES_DB_DIR 2> /dev/null | grep PID | awk -F "PID:" '{print substr($2,2,length($2)-2)}')
elif [ $CURRENT_USER_UID -eq 0 ]; then
    pid=$(su -c "$POSTGRES_STATUS_CMD $POSTGRES_DB_DIR 2> /dev/null" $ADMIN | grep PID | awk -F "PID:" '{print substr($2,2,length($2)-2)}')
else
    return $PERMISSION_DENIED
fi

if [ $pid -eq $pid 2> /dev/null ] && [ $pid -gt 1 2> /dev/null ];then
    if ps -p $pid 2> /dev/null > /dev/null ; then
       # Located the PID
       return $PID_FOUND
    fi
fi

unset pid
return $PID_NOT_FOUND
} 

#
# Function that checks for a service status
#
wg_status() {

found_processid
local status=$?

if [ $status -eq $PID_FOUND ];then
    echo "$NAME (pid $pid) is running"
elif [ $status -eq $PID_NOT_FOUND ]; then
    echo "$NAME is stopped"
else
    echo "$NAME (permission denied)"
fi
}

#
# Function that starts the service.
#
wg_start() {
found_processid
local status=$?

# Set postgresql.conf values and shared memory
if [ $CURRENT_USER_UID -eq 0 ]; then
    /opt/watchguard/dimension/bin/python /opt/watchguard/dimension/lib/python2.7/site-packages/wg_pg/generator.pyc
fi

if [ $EXTERNAL_DB -eq $TRUE ]; then
    # Nothing to do
    return $SUCCESS
fi

if [ $status -eq $PID_NOT_FOUND ];then
    if [ $CURRENT_USER_UID -eq $ADMIN_UID ];then
        echo "Starting $NAME"
         $POSTGRES_START_CMD $POSTGRES_DB_DIR 2> /dev/null > /dev/null &
    else 
        echo "Starting $NAME"
        su -c "$POSTGRES_START_CMD $POSTGRES_DB_DIR 2> /dev/null > /dev/null &" $ADMIN
    fi
    sleep 2
    wg_status
elif [ $status -eq $PID_FOUND ]; then 
    echo "$NAME (pid $pid) is running"
else
    echo "$NAME (permission denied)"
fi
}

#
# Function that stops the service
#
wg_stop() {

found_processid
local status=$?
 
if [ $status -eq $PID_FOUND ];then
    # Check if the user has permission to stop the PID
    kill -0 $pid 2> /dev/null > /dev/null
    status=$?
    if [ $status -eq 0 ];then
        echo "Stopping $NAME (pid $pid)"
        if [ $CURRENT_USER_UID -eq $ADMIN_UID ];then
            $POSTGRES_STOP_CMD $POSTGRES_DB_DIR 2> /dev/null > /dev/null
        else 
            su -c "$POSTGRES_STOP_CMD $POSTGRES_DB_DIR 2> /dev/null > /dev/null" $ADMIN
        fi
        sleep 2
        wg_status
    else
        echo "$NAME (permission denied)"
    fi
elif [ $status -eq $PID_NOT_FOUND ];then
    echo "$NAME is stopped"
else
    echo "$NAME (permission denied)"
fi
}

#
# Function that reloads the service.
#
wg_reload() {

found_processid;
local status=$?

if [ $status -eq $PID_FOUND ];then
    # Check if the user has permission to reload the process
    kill -0 $pid 2> /dev/null > /dev/null
    status=$?
    if [ $status -eq 0 ];then
        echo "Reloading $NAME (pid $pid)"
        if [ $CURRENT_USER_UID -eq $ADMIN_UID ];then
            $POSTGRES_RELOAD_CMD $POSTGRES_DB_DIR 2> /dev/null > /dev/null
        else 
            su -c "$POSTGRES_RELOAD_CMD $POSTGRES_DB_DIR 2> /dev/null > /dev/null" $ADMIN
        fi
    else
        echo "$NAME (permission denied)"
    fi
elif [ $status -eq $PID_NOT_FOUND ]; then
    echo "$NAME is stopped"
else
    echo "$NAME (permission denied)"
fi
}

#
# Function: retrieve_required_fields
# Purpose:  Attempt to read required values EXTERNAL_DB and POSTGRES_DB_DIR
# Return: 0 = Success    1=Error
retrieve_required_fields() {
EXTERNAL_DB=1
POSTGRES_DB_DIR=""

if [ -r $DB_INI_CONF_FILE ]; then
     EXTERNAL_DB=$(grep "^external_db\>" $DB_INI_CONF_FILE 2> /dev/null  | head -1 | awk -F"=" '{print $2}' | sed -e 's/^ *//' -e 's/ *$//')
     if [ ${#EXTERNAL_DB} -gt 0 ] && [ $EXTERNAL_DB -eq $FALSE ]; then
         POSTGRES_DB_DIR=$(grep "^data_directory\>" $DB_INI_CONF_FILE 2> /dev/null  | head -1 | awk -F"=" '{print $2}' | sed -e 's/^ *//' -e 's/ *$//')
         if [ ${#POSTGRES_DB_DIR} -gt 0 ] && [ -f "${POSTGRES_DB_DIR}/postgresql.conf" ]; then
             return $SUCCESS
         fi
     fi
fi

# An error return from this function halts execution. We need to run start, which raises kernel.shmmax.
# This deals with the case where the log server is installed but not configured.
if [ "$1" = "start" ]; then
    return $SUCCESS
fi
return $ERROR
}

retrieve_required_fields $1
if [ $? -ne $SUCCESS ]; then
    echo "Warning: $NAME is disabled"
    exit $SUCCESS
fi

# Main - The script starts here

case $1 in
    start)
        wg_start
        ;;
    stop)
        wg_stop
        ;;
    reload)
        wg_reload
        ;;
    restart|force-reload)
       wg_stop
       sleep 1
       wg_start
        ;;
    status)
        wg_status
        ;;
    *)
        echo "Usage: $SERVICENAME "
		echo "{start|stop|restart|reload|force-reload|status}"
        exit 1
        ;;
esac

exit $SUCCESS

EOF

# Check the cat return status
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

# Check the chmod return status
chmod 755 $POSTGRES_INITD_SCRIPT > /dev/null
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

chown root:$ADMIN $POSTGRES_INITD_SCRIPT > /dev/null
if [ $? -ne $SUCCESS ]; then
    return $ERROR
fi

# Runlevel check and config
if [ -x $CHKCONFIG_CMD ];then
    $CHKCONFIG_CMD --add $SERVICENAME > /dev/null
    if [ $? -ne $SUCCESS ]; then
       return $ERROR
    fi
elif [ -x $UPDATERC_CMD ]; then
    $UPDATERC_CMD $SERVICENAME start 90 2 3 4 5 . stop 10 0 1 6 . > /dev/null
    if [ $? -ne $SUCCESS ]; then
        return $ERROR
    fi
else
    echo "Unsupported $NAME rc.d Install Type"
    return $ERROR
fi

return $SUCCESS
}

# Function: _install_postgres_service
# Purpose : Install the postgres service
# Return  : 0 = Success   1 = An Error Occured
_install_postgres_service() {

if [ $USE_UPSTART -eq $FALSE ] && [ $USE_SYSTEMD -eq $FALSE ]; then
    if _create_postgres_initd_service; then
        # Success = 0 The service file was created succcesfully
        return $SUCCESS
    fi
elif [ $USE_SYSTEMD -eq $TRUE ]; then
    if _create_postgres_systemd_service; then
        ln -sf $POSTGRES_SERVICE_UNIT /etc/systemd/system/multi-user.target.wants/${SERVICENAME}.service
        # Success = 0 The service file was created succcesfully
        return $SUCCESS
    fi
elif [ $USE_UPSTART -eq $TRUE ]; then
    if _create_postgres_upstart_service; then
        # Success = 0 The service file was created succcesfully
        return $SUCCESS
    fi
else
    echo "Return Code: $Error: Unsupported $NAME install method"
fi

return $ERROR
}

# Function: _increase_shared_mem
# Purpose :  Increase system wide shared memory settings if the current 
#            shared memory value is below the min requirement
# Return  :  0 = Success 1 = An Error Occured
_increase_shared_mem() {
	
local shmmax_value=`sysctl -n kernel.shmmax`
local min_shmmax_value=`expr $MB \* 1024 \* 1024`

if [ $CURRENT_USER_UID -ne 0 ]; then
    return $ERROR
fi

if [ $(echo $shmmax_value|wc -m) -ge 11 ]; then
    # If shmmax_value is set at 64 bit max int, shell thinks it is an illegal number
    shmmax_value="1073741824"
fi

if [ $shmmax_value -lt $min_shmmax_value ]; then

    local page_size=`getconf PAGE_SIZE`
    if [ $? -ne $SUCCESS ]; then
        return $ERROR
    fi

    local shmall=`expr $min_shmmax_value / $page_size`

    # Only the root user will have permission to change sysctl parameters
    echo "Increasing shared memory parameters"
    #echo "    pagesize=($page_size) * kernel.shmall=($shmall) = kernel.shmmax=($min_shmmax_value)"

    # Maximum shared segment size in bytes
    sysctl -w kernel.shmmax=$min_shmmax_value > /dev/null
    if [ $? -ne $SUCCESS ]; then
        return $ERROR
    fi

    # Maximum number of shared memory segments in pages
    sysctl -w kernel.shmall=$shmall > /dev/null
    if [ $? -ne $SUCCESS ]; then
        return $ERROR
    fi
fi

return $SUCCESS
}

# Function: _stop_postgres
# Purpose : Check if Postgres is running.  If so, then stop postgres
# Return  :  0 = Success 1 = An Error Occured
_stop_postgres() {
local retval=$FALSE
local EXTERNAL_DB=$TRUE
local POSTGRES_DB_DIR=""

if [ -r $DB_INI_CONF_FILE ]; then
     EXTERNAL_DB=$(grep "^external_db\>" $DB_INI_CONF_FILE 2> /dev/null  | head -1 | awk -F"=" '{print $2}' | sed -e 's/^ *//' -e 's/ *$//')
     if [ ${#EXTERNAL_DB} -gt 0 ] && [ $EXTERNAL_DB -eq $FALSE ];then
         POSTGRES_DB_DIR=$(grep "^data_directory\>" $DB_INI_CONF_FILE 2> /dev/null  | head -1 | awk -F"=" '{print $2}' | sed -e 's/^ *//' -e 's/ *$//')
         if [ ${#POSTGRES_DB_DIR} -le 0 ] || [ ! -f "${POSTGRES_DB_DIR}/postgresql.conf" ]; then
             POSTGRES_DB_DIR=""
             EXTERNAL_DB=$TRUE
         fi
     fi
fi

if [ $EXTERNAL_DB -eq $FALSE ] && [ -x $SERVICE_CMD ]; then
    if [ -f $POSTGRES_UPSTART_CONF ] || [ -f $POSTGRES_INITD_SCRIPT ]; then
        $SERVICE_CMD $SERVICENAME stop 
    fi
fi

# Systemd case
if [ $EXTERNAL_DB -eq $FALSE ] && [ -x $SYSTEMCTL_CMD ]; then
    if [ -f $POSTGRES_SERVICE_UNIT ]; then
        $SYSTEMCTL_CMD stop $SERVICENAME
    fi
fi

return $SUCCESS
}

# Function: _uninstall_postgres_service
# Purpose : Uninstall the postgres service
# Return  :  0 = Success 1 = An Error Occured
_uninstall_postgres_service() {
   
if [ -f $POSTGRES_INITD_SCRIPT ]; then
    if [ -x $CHKCONFIG_CMD ]; then
        $CHKCONFIG_CMD --del $SERVICENAME > /dev/null
        if [ $? -ne $SUCCESS ]; then
            echo "Return Code: $ERROR - $NAME is unable to successfully execute $CHKCONFIG_CMD"
            return $ERROR
        fi
    fi

    rm -f $POSTGRES_INITD_SCRIPT 2> /dev/null > /dev/null
    if [ $? -ne $SUCCESS ]; then
        echo "Return Code: $ERROR - $NAME is unable to remove $POSTGRES_INITD_SCRIPT"
        return $ERROR
    fi

    if [ -x $UPDATERC_CMD ]; then
        $UPDATERC_CMD $SERVICENAME remove > /dev/null
        if [ $? -ne $SUCCESS ]; then
            echo "Return Code: $ERROR - $NAME is unable to successfully execute $UPDATERC_CMD"
            return $ERROR
        fi
    fi
fi

if [ -f $POSTGRES_UPSTART_CONF ]; then
     rm -f $POSTGRES_UPSTART_CONF 2> /dev/null > /dev/null
     if [ $? -ne $SUCCESS ]; then
         echo "Return Code: $ERROR - $NAME is unable to remove $POSTGRES_UPSTART_CONF"
         return $ERROR
     fi
fi

# Systemd case
if [ -f $POSTGRES_SERVICE_UNIT ]; then
    $SYSTEMCTL_CMD disable $SERVICENAME 2> /dev/null > /dev/null
    rm -f $POSTGRES_SERVICE_UNIT 2> /dev/null > /dev/null
    if [ $? -ne $SUCCESS ]; then
        echo "Return Code: $ERROR - $NAME is unable to remove $POSTGRES_SERVICE_UNIT"
        return $ERROR
    fi
fi

return $SUCCESS
}

# Function: _show_usage
# Purpose : Show valid command line paramters and exit the program
# Return  : 1 = An Error Occured
_show_usage() {
echo ""
echo "Purpose:"
echo "$DESC"
echo ""
echo "Usage:"
echo " $0 [-install] [-uninstall [-clean]]"
echo ""
echo "Examples: - Must run as root -"
echo ""
echo "To install $NAME"
echo "$0 -install"
echo ""
echo "To uninstall $NAME"
echo "$0 -uninstall"
echo ""

exit $ERROR
}

# 
# Main Body - The script starts here
#

# Required Common Variables

if [ -r /etc/default/wg_pg_service ]; then
    . /etc/default/wg_pg_service
else
    # Nothing to do
    exit 0
fi


SERVICENAME="wg_pg_service"
NAME="Watchguard PostgreSQL Service"
DESC="Provides the builtin PostgreSQL database for WatchGuard Servers"
POSTGRES_SERVICE_UNIT="/etc/systemd/system/${SERVICENAME}.service"
POSTGRES_UPSTART_CONF="/etc/${SERVICENAME}.conf"
POSTGRES_INITD_SCRIPT="/etc/init.d/${SERVICENAME}"
POSTGRES_CTL_CMD="${WG_BINDIR}/pg_ctl"
POSTGRES_START_PARAMS="-o '-h \\\"\\\"' start -D"
POSTGRES_START_CMD="${POSTGRES_CTL_CMD} $POSTGRES_START_PARAMS"
POSTGRES_STOP_PARAMS="stop -m fast -D"
POSTGRES_STOP_CMD="${POSTGRES_CTL_CMD} $POSTGRES_STOP_PARAMS"
POSTGRES_RELOAD_PARAMS="reload -D"
POSTGRES_RELOAD_CMD="${POSTGRES_CTL_CMD} $POSTGRES_RELOAD_PARAMS"
POSTGRES_STATUS_PARAMS="status -D"
POSTGRES_STATUS_CMD="${POSTGRES_CTL_CMD} $POSTGRES_STATUS_PARAMS"
SYSTEMCTL_CMD="/usr/bin/systemctl"
SERVICE_CMD="/usr/sbin/service"
CHKCONFIG_CMD="/sbin/chkconfig"
UPDATERC_CMD="/usr/sbin/update-rc.d"
CURRENT_USER_UID=`id -u`

ADMIN=$WG_ADMIN_USER
DB_INI_CONF_FILE="${WG_ETCDIR}/postgres/postgres.ini"

TRUE=1
ERROR=1
FALSE=0
SUCCESS=0
 
USE_SYSTEMD=$TRUE     # Set USE_SYSTEMD to TRUE
USE_UPSTART=$FALSE    # Set USE_UPSTART to FALSE - Upstart is not supported at this time
MB=256                # Megabytes needed for Postgres shared memory                          
PATH="${WG_BINDIR}:/sbin:/bin:/usr/sbin:/usr/bin"

# Must run this script as root, and the parameter count must equal one
if [ $CURRENT_USER_UID -ne 0 ] ; then
    _show_usage
fi

if [ $USE_SYSTEMD -eq $TRUE ]; then
    _is_systemd_installed
    if [ $? -eq $FALSE ]; then
        # systemd and systemd-sysv are not installed
        USE_SYSTEMD=$FALSE
    fi
fi

if [ $USE_UPSTART -eq $TRUE ]; then
    _is_upstart_installed
    if [ $? -eq $FALSE ]; then
        # Upstart executables are not installed
        USE_UPSTART=$FALSE
    fi
fi
case $1 in 
    -install)
        _increase_shared_mem
        if [ $? -ne $SUCCESS ]; then
            echo "Error: $NAME failed to increase shared memory"
            exit $ERROR
        fi
        if _install_postgres_service; then
            echo "$NAME installed successfully"
        else
            echo "Error: $NAME failed to install"
            exit $ERROR
        fi
    ;;
    -uninstall)
        _stop_postgres
        if [ $? -ne $SUCCESS ]; then
            echo "Return Code: $ERROR - $NAME is unable to stop the database!"
            return $ERROR
        fi
        if _uninstall_postgres_service; then
            echo "$NAME uninstalled successfully"
        else
            echo "Error: $NAME failed to uninstall"
            exit $ERROR
        fi    
        if [ "$2" = "-clean" ] ; then
            echo "Cleaning up $NAME data"
            rm -rf ${WG_ETCDIR}/postgres || true
        fi
    ;;
    *)
        _show_usage
    ;;
esac
