#!/bin/bash
######################################################################################################################
# BASH Server-Side Login/Generic script
# by Giovanni Frainer <user-e1d5cb184a81@xymon.invalid>
# Based on the Perl version and Hobbit documentation made by
# Henrik Storner <user-ce4a2c883f75@xymon.invalid> 
#
# Instalation:
# 	1. Put this script in server/ext/rootlogin.sh (chmod +x on the file)
#	2. Insert the name of this script inside every host monitored by in server/etc/bb-hosts
#		Ex: 10.10.10.10 servername.domain.com # login
#	3. Register the script to HobbitLaunch, in server/etc/hobbitlaunch.cfg
#		[rootlogin]
#			ENVFILE /home/hobbit/server/etc/hobbitserver.cfg
#			NEEDS hobbitd
#			CMD hobbitd_channel --channel=client --log=$BBSERVERLOGS/rootlogin.log $BBHOME/ext/rootlogin.sh
#	4. Restart hobbit and wait 5 min max. :-)
#######################################################################################################################
#
#
# The home of your Hobbit Server
BBHOME="/home/hobbit/server"

# Global Variables
. ${BBHOME}/etc/hobbitserver.cfg

# The name of the column
COLUMN="login"

# The section in client-data that
# will be stored
GRABSECTION="who"

# The file that stores the section
TMPFILE="${BBTMP}/${COLUMN}"

######################### The Test itself ###############################
# this function will be called on every event
process() {
/home/hobbit/server/bin/bbhostgrep ${COLUMN} | \
	while read L; do
		set $L

		HOSTIP="$1"
		MACHINEDOTS="$2"
		MACHINE=`echo $2 | sed -e 's/\./,/g'`

		if [ "${MACHINEDOTS}" == "${SERVER}" ]; then

			### The script itself ###
			if [ "$(cat ${TMPFILE} | grep -w "root")" != "" ]; then
				# red maybe ?
				MSG="&yellow Root logged in!"
				COLOR="yellow"
			else
				# Everything normal
				MSG="&green No root login at the moment."
				COLOR="green"
			fi
	
			$BB $BBDISP "status $MACHINE.$COLUMN $COLOR `date`
${MSG}

$(cat ${TMPFILE})"
			#########################
		fi


	done
}

###########################################################################

# Part of the script who handles the requests and send them to the
# process function

rm -f ${TMPFILE}
FOUND=0
STARTED=0
while read LINE; do

	# Register the Server Name	
	if [ ${STARTED} -eq 0 ]; then
		SERVER="$(echo ${LINE} | awk -F\| '{ print $4 }')"
		STARTED=1
	fi

	# Found the section!
	if [ "${LINE}" == "[${GRABSECTION}]" ]; then
		FOUND=1
		continue
	fi

	# Register the section of the client-data to the temporary file
	if   [ "$(echo ${LINE} | egrep -E '^\[*[a-z]*\]$')" == "" ] && [ ${FOUND} -eq 1 ]; then
		echo ${LINE} >> ${TMPFILE}
	# Section ended
	elif [ "$(echo ${LINE} | egrep -E '^\[*[a-z]*\]$')" != "" ] && [ ${FOUND} -eq 1 ]; then
		FOUND=0
		continue
	# Event ended
	elif [ "$(echo ${LINE} | egrep -E '^@@$')" != "" ] && [ ${STARTED} -eq 1 ]; then
		process
		rm -f ${TMPFILE}
		STARTED=0
	fi
done

# Cleanup
exit 0
