#!/bin/bash

. ${TOOLKIT}-functions.sh

USER="nagios"
GROUP="nagios"
WWW_GROUP=$(jtconf apache.group)

FILEMODE_RO="440"
FILEMODE_CFG="660"
DIRMODE_CFG="2770"

# fixes messy on /usr/share
#
cd /usr/share
[ -L nagios ] || {
	echo "  fixing /usr/share/nagios -> /usr/share/nagios3"
	cd nagios
	tar cf - * | tar xf - -C /usr/share/nagios3
	cd ..
	rm -rf nagios
	ln -s nagios3 nagios
}



cd /etc/nagios3

# move default (sample) config files to backup dir
#
bckdir="conf.d-original"
for file in $(ls conf.d/*_nagios2.cfg 2>/dev/null)
do
	echo " sample moved to $bckdir: $file"
	mv $file $bckdir/.
	SOMETHING_CHANGED=true
done


# build list of auto checked hosts
# --------------------------------
#
# we assume a simple standardized network structure like this:
#
#	+----(lan)---[gw]---[wan_gw (router)]---> (internet)
#       |
#       +-server
#	+-host_1
#	+-host_2
#	+-....
#	+-host_n
#
# - we setup an "alive" (ping) check for each host
#
# - duplicate hosts are detected (eg: the server is also the gw)
#
# - for each named host (gw, server, wan_gw) we auto generate
#   checks for predefined services, using <name>_services db entry
#
# - "internet" is a fake named host, so no services are defined/used
#
# - nagios.quick_check_hostlist can contain a list of other hosts
#   to avail-check; services for this hosts must be defined manually
#
# - as in figure, each host listed will depends from 'gw', except of
#   course of 'gw' itself
#
# - to disable one of the named hosts, joust define empty name or ip
#
declare -A processed

customer_code=$(jtconf customer.code)
autodir="/etc/nagios3/kusa-auto"
svcdir="$autodir/services"

for dir in $autodir $svcdir
do
	[ -d $dir ] || mkdir $dir
done


for host in gw server wan_gw internet hostgroup
do
	src="auto-checks/$host"

	name=$(jtconf nagios.${host}_name 2>/dev/null) || :
	ip=$(jtconf nagios.${host}_ip 2>/dev/null) || :
	nodetype=$(jtconf nagios.${host}_nodetype 2>/dev/null) || :

	name=$(echo $name | sed -e 's/\..*//')	# strip domain from name

	export tmp_nagios_nodetype=	# used in templates

	[ "X$nodetype" != "X" ] && tmp_nagios_nodetype="-$nodetype"

	case $host in
	  gw)	# name or ip undefined? error
	  	[ "X$name" = "X" -o "X$ip" = "X" ] && {
			echo "ERROR: nagios.gw_name and nagios.gw_ip must be defined and not emtpy" >&2
			exit 1
		}
		export tmp_nagios_gw_name="${customer_code}_${name}"	# used in templates
		;;
	  wan_gw)
		export tmp_nagios_wan_gw_name="${customer_code}_${name}"	# used in templates
	  	;;
	  hostgroup)
	  	# no needs for name or ip, fake name
		name="hostgroup"
	  	;;
	  *)	# name or ip undefined? ignore entry
	  	[ "X$name" = "X" -o "X$ip" = "X" ] && {
	  		continue
		}
	esac

	export tmp_nagios_name=$name		# use this in templates


	[ ${processed[$name]:-'false'} == 'true' ] && continue

	file="$autodir/${host}.cfg"
	installfile $src $file $USER:$GROUP $FILEMODE_RO
	processed[$name]='true'
	processed[$file]='true'

	# add custom services for this host
	#
	services=$(jtconf nagios.${host}_services 2>/dev/null) || :

	[ "X$services" != "X" ] && {
	  case $host in
	    internet)
	    	echo "  warning: nagios.internet_services ignored" ;;
	    *)
		for service in $(jtconf nagios.${host}_services)
		do
			filename="${host}-$service"
			file="$svcdir/$filename.cfg"
			export tmp_nagios_service=$service
			export tmp_nagios_host_name=$name
			installfile auto-checks/service $file $USER:$GROUP $FILEMODE_RO
			processed[$filename]='true'
			processed[$file]='true'
		done
		;;
	  esac
	}

	# add standardized services to host
	#
	here=$(pwd)
	cd $svcdir

	std_services=$(jtconf nagios_stdservices.$nodetype 2>/dev/null) || :
	name="${customer_code}_$name"

	for service in $std_services
	do
		parms=

		# format SERVICE,PARMS
		case $service in
		  *,*)	parms=$(echo "$service" | cut -d',' -f2)
		  	parms=$(echo "$parms" | tr ',' ' ')
		  	service=$(echo "$service" | cut -d',' -f1)
			;;
		esac

		filename="${name}-$service"
		file="$svcdir/$filename.cfg"
		ku-nagios-mkcheck $service $name $parms
		echo "# AUTOGENERATED" >>$file
		chmod $FILEMODE_RO $file
		processed[$filename]='true'
		processed[$file]='true'
	done
	cd $here
done

# add other hosts from quick list using a basic template
#
quick_hostlist=$(jtconf nagios.quick_check_hostlist 2>/dev/null) || :
default_gw=$tmp_nagios_gw_name

for name in $quick_hostlist
do
	nodetype="DEFAULT"
	tmp_nagios_gw_name=$default_gw

	# format PARENT:NAME
	case $name in
	  *:*)	tmp_nagios_gw_name=$(echo "$name" | cut -d':' -f1)
	  	name=$(echo "$name" | cut -d':' -f2)
		;;
	esac

	# format NAME:IPADDR (or real dns name)
	case $name in
	  *,*)	ip=$(echo "$name" | cut -d',' -f2)
	  	name=$(echo "$name" | cut -d',' -f1)
		;;
	  *)	ip=$name
	  	;;
	esac

	# format NAME/NODETYPE
	case $name in
	  */*)	nodetype=$(echo "$name" | cut -d'/' -f2)
	  	name=$(echo "$name" | cut -d'/' -f1)
		;;
	esac

	case $name in
	  *.*)	name=$(echo $name | sed -e 's/\..*//')	# strip domain from name
	  	;;
	esac

	export tmp_nagios_name=$name		# use this in templates

	[ ${processed[$name]:-'false'} != 'true' ] || continue

	export tmp_nagios_name=$name
	export tmp_nagios_nodetype=$nodetype
        export tmp_nagios_alias=
        export tmp_nagios_ip=$name
	file="$autodir/${name}.cfg"
	installfile auto-checks/quick-host $file $USER:$GROUP $FILEMODE_RO
	processed[$name]='true'
	processed[$file]='true'

	# add standardized services to host
	#
	here=$(pwd)
	cd $svcdir

	std_services=$(jtconf nagios_stdservices.$nodetype 2>/dev/null) || :

	for service in $std_services
	do
		parms=

		# format SERVICE,PARMS
		case $service in
		  *,*)	parms=$(echo "$service" | cut -d',' -f2)
		  	parms=$(echo "$parms" | tr ',' ' ')
		  	service=$(echo "$service" | cut -d',' -f1)
			;;
		esac

		filename="${name}-${service}"
		file="$svcdir/$filename.cfg"
		ku-nagios-mkcheck $service $name $parms
		echo "# AUTOGENERATED" >>$file
		chmod $FILEMODE_RO $file
		processed[$filename]='true'
		processed[$file]='true'
	done
	cd $here
done

# finally, purge obsolete auto files
#
for file in $(grep -lR '# AUTOGENERATED' $autodir)
do
	[ -f "$file" ] || continue

	[ ${processed[$file]:-'false'} != 'true' ] && {
		echo "  remove obsolete auto definition: $file"
		rm -f "$file"
		SOMETHING_CHANGED=true
	}
done



#----------------------------------------------------------------------------
# EXTERNAL COMMANDS
#----------------------------------------------------------------------------

echo -n "  external commands check: "
needs_update_dpkg=false

if [ "X$(jtconf nagios_options.check_external_commands)" = "X1" ]
then
	echo ENABLED

	dir="/var/lib/nagios3/rw"
	prev_stat=$(ls -ld $dir)
	create_dir --fixperms $dir $USER:$WWW_GROUP 2710
	[ "X$(ls -ld $dir)" != "X$prev_stat" ] && needs_update_dpkg=true

	dir="/var/lib/nagios3"
	prev_stat=$(ls -ld $dir)
	create_dir --fixperms $dir $USER:$GROUP 751
	[ "X$(ls -ld $dir)" != "X$prev_stat" ] && needs_update_dpkg=true

	# avoid changes during updates
	$needs_update_dpkg && {
		/etc/init.d/nagios3 stop
		dpkg-statoverride --list /var/lib/nagios3/rw >/dev/null || {
			dpkg-statoverride --update --add $USER $WWW_GROUP 2710 /var/lib/nagios3/rw
		}
		dpkg-statoverride --list /var/lib/nagios3 >/dev/null || {
			dpkg-statoverride --update --add $USER $GROUP 751 /var/lib/nagios3
		}
		/etc/init.d/nagios3 start
	}
else
	echo DISABLED
fi


# fix perms in config dirs
#
dir="/etc/nagios3/conf.d"
chown -R $USER:$GROUP $dir
chmod -R $FILEMODE_CFG $dir
find $dir -type d -exec chmod $DIRMODE_CFG {} \;



$SOMETHING_CHANGED && {
	reload_service nagios3 nagios3 || exit 1
}

exit 0
