#!/bin/sh

# Shell script to stop dhclient on an interface on RHEL

if_name="$1"

pids=$(/opt/vmware/nsx-opsagent/libexec/nsxaCmd ps -o pid,cmd -C "dhclient" | awk '$9 == "'${if_name}'" || $11 == "'${if_name}'" {print $1}' | sort -n)
if [ -n "${pids}" ]
then
    echo "${pids}" | \
    while read line
    do
        /opt/vmware/nsx-opsagent/libexec/nsxaCmd kill -15 ${line} > /dev/null 2>&1
    done
    # Many times dhclient will not respond to SIGTERM,
    # in that case, send SIGKILL
    sleep 1
    echo "${pids}" | \
    while read line
    do
        if ! ps ax | awk '$1 == '${line}' {exit 1}' > /dev/null 2>&1
        then
            /opt/vmware/nsx-opsagent/libexec/nsxaCmd kill -9 ${line} > /dev/null 2>&1
        fi
    done
fi

if [ -s /var/lib/dhclient/dhclient-${if_name}.leases ]
then
    /opt/vmware/nsx-opsagent/libexec/nsxaCmd rm -f /var/lib/dhclient/dhclient-${if_name}.leases > /dev/null 2>&1
fi

exit
