#!/bin/bash
################################################################################
# Copyright (c) 2013-2017 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] [OS_USER]"
   echo "Example: `basename $0` TERM vpostgres"
   exit $ERROR_NUM
}

# Wrapper to log given message to stderr, which is something that
# can be digested by vMon when running this script as part of the
# pre-start command of service vmware-vpostgres.
log_stderr()
{
   >&2 echo ${1}
}

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
   log_stderr "Signal can just be set as TERM or KILL"
   exit 1
fi

OS_USER=$2

# For simplicity, this routine uses pkill to hunt and kill all postgres
# processes run by the OS user defined by $OS_USER.
log_stderr "Issuing signal $KILL_SIGNAL on all PostgreSQL processes owned by OS user $OS_USER"
/usr/bin/pkill -$KILL_SIGNAL -x postgres -u $OS_USER
