#!/bin/sh

YULERC="/etc/yulerc"
YULEDIR="/var/lib/yule"
YULELOG="/var/log/yule/yule_log"
YULEUSER="yule"
YULEGROUP="yule"
YULERESTART="/sbin/service yule restart"

deploybin="/usr/local/sbin/deploy.sh"

# this is used for creating hosts only
# (to check if this is a valid host)
# if you uncomment it, this check will not be performed
FORCEDOMAIN="yourdomain.net"

action_dbclear="/usr/local/sbin/samhain.clearhost"


geth() {
	unset HLIST
	unset FQHLIST
	
	for file in $(ls ${YULEDIR}/file* | egrep -v ".bak$" | egrep -v ".log$" | \
		egrep -v ".mgmt$" | egrep -v ".old$" | egrep -v ".sav$" ) ;  do
		# strip path
		fn=$(basename ${file})
		# strip leading "file."
		fqhn=${fn#file.}
		# strip trailing domain
		hn=${fqhn%%.*}
		# write results to two arrays
		FQHLIST[${#FQHLIST[*]}]=$fqhn
		HLIST[${#HLIST[*]}]=$hn
	done
	
	# get the length of the two arrays
	hlistlen=${#HLIST[*]}
	fqhlistlen=${#FQHLIST[*]}

	# run until a valid selection is made
	while [ 1 ] ; do
		clear
		echo "HOST LIST SELECTION"
		echo
		
		# loop through array, print echo each host
		arrpos=0
		while [ ${arrpos} -lt ${hlistlen} ] ; do
			echo -e "$((${arrpos}+1)).\t${HLIST[${arrpos}]}"
			arrpos=$((${arrpos}+1))
		done
		
		echo
		echo -n "Please select a host (q to quit): "
		 
		read hostsel
		
		if [ "${hostsel}" = "q" ] ; then
			exit
		fi

		isnum=$(echo ${hostsel} | egrep "^[[:digit:]]*$")
		if [ "${isnum}" ] ; then
			if [ ${hostsel} -gt 0 -a ${hostsel} -lt $((${hlistlen}+1)) ]
			then
				hostsel=$((${hostsel}-1))
				break
			fi
		fi
	done
}


getprof() {
	unset PLIST
	for entry in $(find ${YULEDIR}/profiles -type d -maxdepth 1) ; do
		entry=$(basename ${entry})
		if [ ! "${entry}" = "src" -a ! "${entry}" = "profiles" ] ; then
			PLIST[${#PLIST[*]}]=${entry}
		fi
	done
	
	# array length
	plistlen=${#PLIST[*]}
}




cleardb() {
# clear the SQL database
	geth
	(
		echo "Clearing database for ${HLIST[${hostsel}]}:"
		${action_dbclear} ${HLIST[${hostsel}]} 2>&1 && \
			echo "exit 0"
	) | less
} 



# re-init part
rrinit() {

	geth

	if [ ! -f ${YULEDIR}/file.${FQHLIST[${hostsel}]} ] ;  then
		echo "File ${YULEDIR}/file.${FQHLIST[${hostsel}]} does not exist. Exiting."
		exit 42
	fi

	if [ ! -f ${YULEDIR}/rc.${FQHLIST[${hostsel}]} ] ;  then
		echo "File ${YULEDIR}/rc.${FQHLIST[${hostsel}]} does not exist. Exiting."
		exit 42
	fi

	echo "Please see the yule log if you really want to reinit the samhain database."
	echo "This is a really ugly XML file. Better get out of here ..."
	echo -n "Press ENTER to continue. "
	read forgetthisone


	while [ 1 ] ; do
		grep "remote_host=\"${HLIST[${hostsel}]}\"" ${YULELOG} | less
	
		echo -n "Now that you've seen this: do you still want to continue? (y) (q to quit): "
		read goforit

		if [ "${goforit}" = "q" ] ; then
			exit
		fi

		if [ "${goforit}" = "y" ] ; then
			break
		fi
	done


	# Clean the database
	echo "Clearing database for ${HLIST[${hostsel}]}:"
	${action_dbclear} ${HLIST[${hostsel}]} 2>&1 && echo "exit 0"


	# now run remotely
	# this code is _really_ funny ... :)
	ssh -x root@${FQHLIST[${hostsel}]} \
	'if [ ! -d /samhain-deploy ] ; then \
	        mkdir /samhain-deploy ; \
	fi ; \
	if [ -f /samhain-deploy/sh_database ] ; then \
		rm -f /samhain-deploy/sh_database ; \
	fi ; \
	if [ -x /usr/bin/monit -a "$(/usr/bin/monit status | grep samhain)" ] ; then \
	        monit stop samhain && sleep 5 ; \
	elif [ -x /etc/init.d/samhain ] ; then \
	        /etc/init.d/samhain stop ; \
	elif [ -x /etc/rc.d/init.d/samhain ] ; then \
	        /etc/rc.d/init.d/samhain stop ;
	else \
		kill $(cat /var/run/samhain.pid) ; \
	fi ; \
	/sbin/samhain -t init '
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a'

	# backup old database
	cp ${YULEDIR}/file.${FQHLIST[${hostsel}]} ${YULEDIR}/file.${FQHLIST[${hostsel}]}.mgmt

	# get the new database
	scp root@${FQHLIST[${hostsel}]}:/samhain-deploy/sh_database \
		${YULEDIR}/file.${FQHLIST[${hostsel}]} && \
	chown  ${YULEUSER}:${YULEGROUP} ${YULEDIR}/file.${FQHLIST[${hostsel}]} && \
	chmod 600 ${YULEDIR}/file.${FQHLIST[${hostsel}]}
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a' ; sleep 1
	echo -n -e '\a'

	while [ 1 ] ; do
		echo
		echo -n "Do you want to start the remote samhain client now? (y/n/q) "
		read remotestart
		
		if [ "${remotestart}" = "q" ] ; then
			exit
		fi		

		if [ "${remotestart}" = "y" -o "${remotestart}" = "n" ] ; then
			break
		fi
	done

	if [ "${remotestart}" = "y" ] ; then
		# restart samhain on remote host
		ssh -x root@${FQHLIST[${hostsel}]} \
	        'if [ -f /samhain-deploy/sh_database ] ; then \
	                rm -f /samhain-deploy/sh_database ; \
	        fi ; \
		if [ -x /usr/bin/monit -a "$(/usr/bin/monit status | grep samhain)" ] ; then \
	        monit start samhain ; \
		elif [ -x /etc/init.d/samhain ] ; then \
		        /etc/init.d/samhain start ; \
		elif [ -x /etc/rc.d/init.d/samhain ] ; then \
		        /etc/rc.d/init.d/samhain start ;
		else \
		        echo "Do not know how to start samhain." ; \
		fi'
		echo -n -e '\a' ; sleep 1
		echo -n -e '\a' ; sleep 1
		echo -n -e '\a' ; sleep 1
       		echo -n -e '\a' ; sleep 1
		echo -n -e '\a'
		
		echo "done"
	fi
}


# add a new host
addnewhost() {
	getprof

	while [ 1 ] ; do
	        clear
	        echo "PROFILE SELECTION"
	        echo
	        
	        # loop through array, print echo each host
	        arrpos=0
	        while [ ${arrpos} -lt ${plistlen} ] ; do
	                echo -e "$((${arrpos}+1)).\t${PLIST[${arrpos}]}"
	                arrpos=$((${arrpos}+1))
	        done
	        
	        echo
	        echo -n "Please select a profile (q to quit): "
	
	        read psel
	
	        if [ "${psel}" = "p" ] ; then
	                exit
	        fi
	
		if [ ${psel} -gt 0 -a ${psel} -lt $((${plistlen}+1)) ] ; then
                	psel=$((${psel}-1))
                	break
		fi
	done

	while [ 1 ] ; do
		echo
		echo -n "Enter a fully qualified host name: "
		read newhost
		foundpoint=$(echo ${newhost} | egrep "\.")
		if [ "${foundpoint}" ] ; then
			break
		else
			echo "Dude, a FQHN please!"
			continue
		fi
		if [ "${FORCEDOMAIN}" ] ; then
			if [ "$(echo ${newhost} | egrep \"\.${FORCEDOMAIN}$\")" ] ; then
				break
			else
				echo "Host must be in domain ${FORCEDOMAIN}"
				continue
			fi
		fi
	done


	while [ 1 ] ; do
		echo "You are going to run the following command:"
		echo "${deploybin} --remote-host=${newhost} --build-OS=${PLIST[${psel}]} --clients=${YULERC}"
		echo -n "Continue? (y/n/q) "
		read pconf

		if [ "${pconf}" = "q" ] ; then
			exit
		fi

		if [ "${pconf}" = "y" -o "${pconf}" = "n" ] ; then
			break
		fi
	done

	if [ ${pconf} = "y" ] ; then
		${deploybin} --remote-host=${newhost} --build-OS=${PLIST[${psel}]} --clients=${YULERC}


		chown ${YULEUSER}:${YULEGROUP} ${YULEDIR}/file.${newhost} ${YULEDIR}/rc.${newhost}

		while [ 1 ] ; do
			echo
			echo "Yule has to be restarted before the client is started."
			echo -n "Do you want to restart yule now? (y|n) "
			read yulerestart
	
			if [ "${yulerestart}" = "y" -o "${yulerestart}" = "n" ] ; then
				break
			fi
		done
	
		if [ "${yulerestart}" = "y" ] ; then
			eval ${YULERESTART}
		fi


		while [ 1 ] ; do
			echo
			echo -n "Do you want to start the remote samhain client now? (y|n) "
			read startsam
			if [ "${startsam}" = "y" -o "${startsam}" = "n" ] ; then
	                        break
	                fi
		done


		if [ "${startsam}" = "y" ] ; then

			echo "x${newhost}x"

			ssh -x root@${newhost} \
			'if [ -f /var/run/samhain.pid ] ; then \
				if [ -x /usr/bin/monit -a "$(/usr/bin/monit status | grep samhain)" ] ; then \
					monit stop samhain && sleep 5 ; \
				elif [ -x /etc/init.d/samhain ] ; then \
					/etc/init.d/samhain stop ; \
				elif [ -x /etc/rc.d/init.d/samhain ] ; then \
					/etc/rc.d/init.d/samhain stop ;
				else \
					kill $(cat /var/run/samhain.pid) ; \
				fi ; \
			fi ; \
			if [ -x /usr/bin/monit -a "$(/usr/bin/monit status | grep samhain)" ] ; then \
				monit start samhain ; \
			elif [ -x /etc/init.d/samhain ] ; then \
				/etc/init.d/samhain start ; \
			elif [ -x /etc/rc.d/init.d/samhain ] ; then \
				/etc/rc.d/init.d/samhain start ;
			else \
				echo "Do not know how to start samhain." ; \
			fi'
	                echo -n -e '\a' ; sleep 1
	                echo -n -e '\a' ; sleep 1
	                echo -n -e '\a' ; sleep 1
	                echo -n -e '\a' ; sleep 1
	                echo -n -e '\a'
	        fi
	fi


}




# run until a valid selection is made
while [ 1 ] ; do
	clear
	
	echo "SELECT ACTION"
	echo
	
	echo -e "1.\tOnly clear log entries in SQL database"
	echo -e "2.\tReinitialize host database"
	echo -e "3.\tAdd a new host"
	echo
	echo -n "Select an action (q to quit): "
	
	read action
	
	if [ "${action}" = "q" ] ; then
                exit
        fi

	if [ "${action}" = "1" ] ; then
		cleardb
	fi

	if [ "${action}" = "2" ] ; then
		rrinit
	fi

	if [ "${action}" = "3" ] ; then
		addnewhost
	fi

done




