#!/bin/bash
################################################################################
# Copyright (c) 2013-2016 VMware, Inc. All rights reserved.
################################################################################
# Cleans-up orphaned child processes if postmaster is not running. This is
# aimed at being used by vMon or any similar utility commands as a pre-start
# cleanup command should Postgres be taken down by kill-9 or similar.
# This script should be run as root.

ENCODING=UTF8
THIS_DIR=`dirname $0`

if [ -z $VMWARE_POSTGRES_BASE ]; then
   echo "VMWARE_POSTGRES_BASE is not set."
   echo "Check your installation."
   exit 1
fi
SANITY_FILE=$VMWARE_POSTGRES_BASE/scripts/vpostgres_sanity_checks
if [ -f $SANITY_FILE ]; then
   source $SANITY_FILE
else
   echo "Sanity check file for environment variables of VMware Postgres"
   echo "is not available. Check your installation."
   exit 1
fi

# Show utility help
show_help()
{
   ERROR_NUM=$1
   echo "Usage: `basename $0` [TERM|KILL] [WAIT_TIME]"
   echo "Example: `basename $0` TERM 30"
   exit $ERROR_NUM
}

EXPECTED_ARGS=2
if [ $# -ne $EXPECTED_ARGS ]; then
   # Leave with an error code
   show_help 1
fi

# Type of signal to use, either TERM or KILL
KILL_SIGNAL=$1
if [ $KILL_SIGNAL != "TERM" -a $KILL_SIGNAL != "KILL" ]; then
   echo "Signal can just be set as TERM or KILL"
   exit 1
fi

# How long to wait for Postgres to terminate (in seconds)
KILL_WAIT=$2
KILL_WAIT_CHECK=`echo $KILL_WAIT | tr -d "[:digit:]"`
if [ ! -z $KILL_WAIT_CHECK ]; then
   echo "$KILL_WAIT is not an integer"
   exit 1
fi

# For simplicity, this routine uses pgrep/pkill to hunt and kill all
# postgres processes. To support killing a specific instance (e.g. when
# more than one postgres instances), this routine could be modified to
# iterate over pids with `readlink /proc/$pid/cwd` == $PGDATA.
if /usr/bin/pgrep -x $POSTGRES -u $VMWARE_POSTGRES_OS_ADMIN >/dev/null 2>&1 ; then
   # Treat exit code 7 "Program was not running to receive the
   # specified signal as 'not an error'.
   /sbin/killproc -$KILL_SIGNAL -t $KILL_WAIT "${VMWARE_POSTGRES_BIN}/postgres" || test "$?" == "7" || { echo "failed to kill orphan processes." ; exit 1 ; }
fi
