#!/bin/bash
#
# This script is invoked by lscfg --delete/--change
# 
# The script finds the active logins present in the VF being 
# deleted or changed and kills the shells of those users
# logging them out of their sessions. 
#

set -e

SED="/bin/sed"

# Determine the internal address of Standby CP

SWBD=`/sbin/sin | $SED -n -e 's/^.\+\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp' 2>/dev/null`
CPID=`/sbin/sin | $SED -n -e 's/^Control.\+No: \([[:digit:]]\{1,\}\)$/\1/gp' 2>/dev/null`
otherhost(){
	case ${SWBD##SWBD} in
	'165' | '166' | '179' | '180')
		printf 127.3.1.$((2 - CPID % 2))
		;;
	'62')
		printf 127.1.1.$((8 - CPID % 2))
		;;
	'77')
		printf 127.1.1.$((6 - CPID % 2))
		;;
	'141')
        printf 127.1.$((17 - CPID % 2)).$((17 - CPID % 2))
        ;;
    '142')
        printf 127.1.$((15 - CPID % 2)).$((15 - CPID % 2))
        ;;
	*)
		printf 10.0.0.$((6 - CPID % 2))
		;;
	esac
}



#Logout the users on Active CP

cd /proc

# Find the PIDs of all shell processes
/usr/bin/find [0-9]*/exe -type l -lname /bin/bash 2>/dev/null | while read p
do
	# Strip off anything following pid
	p=${p%/*}
	# Find the (users) shell pids operating in the VF being deleted or changed
	if /usr/bin/tr '\0' '\n' < $p/environ | grep '^CURRENT_VF='$1'$' > /dev/null
	then
		echo -e "\n\nThe Logical Switch for the FID $1 is being deleted" \
				"or changed. You will be logged out.\n" > $p/fd/2 &
		kill -KILL $p
	fi
done 2>/dev/null



#Logout the users on Standby CP, if it exists and is in HA Sync

if /fabos/bin/hashow | /usr/bin/tr '\n' ' ' | grep "Remote.*Standby.*HA State synchronized.*" > /dev/null ; then
	stbyCP=$(otherhost)
	procs=`/usr/bin/rsh $stbyCP "cd /proc; /usr/bin/find [0-9]*/exe -type l -lname /bin/bash 2>/dev/null"`
	for p in $procs
	do
		p=${p%/*}
		if /usr/bin/rsh $stbyCP "cat /proc/$p/environ" | /usr/bin/tr '\0' '\n' | grep '^CURRENT_VF='$1'$' > /dev/null
		then
			/usr/bin/rsh $stbyCP "echo -e \"\n\nThe Logical Switch for the FID $1 is being deleted or changed. You will be logged out.\n\" > /proc/$p/fd/2; kill -KILL $p"
		fi
	done 2>/dev/null
fi

exit 0
