#!/bin/bash

# KmgVersionString 3.6.0.2

RNDC="/usr/sbin/rndc"
RUNAS="nobody"
RUN="0"
MYSTATE=idle
RUNDIR="/var/phion/run/bdns"
OPCONFDIR="/var/phion/preserve/bdns"
OPCONFFILE=${OPCONFDIR}/bdns.conf 
STATEFILE=${RUNDIR}/bdns.state
NAMEDPIDFLE=${RUNDIR}/bdns.pid
MODULENAME="bdns"
MYPID=$$

PATH="/bin:/sbin:/usr/sbin:/usr/bin/:/etc/phion/bin:/opt/phion/bin"

SYSLOGATTACH=$(which logsetup2) || exit 1


function do_phionlog {
		
	local PMODPATH="/opt/phion/modules/box/boxsrv/${MODULENAME}"

	[ -f ${PMODPATH}/moddefs.conf ] && source ${PMODPATH}/moddefs.conf

	MYLOGFLE="${logfile_modexe:-box_Settings_DNS}"

	if [ -f /etc/phion/phion.sh ]; then
        	source /etc/phion/phion.sh
	fi
	if [ -f /etc/phion/functions ]; then
        	source /etc/phion/functions
	        logerror="LogError $MYLOGFLE"
	else
        	logerror="echo"
	fi
	return 0
}

function setSTATE {
	local ARG1=${1}
	local STATE="unknown"
	case ${ARG1:-} in 
		on|off|idle)
				;;
		*)
				return 1
				;;
	esac
	
	[ -s ${STATEFILE} ] && {
		STATE=$(cat ${STATEFILE}) &>/dev/null
	} 		
	echo ${ARG1} > ${STATEFILE}
	$logerror "Info" "${ARG0}[$$]: set internal state from ${STATE} to ${ARG1}"
}




do_phionlog





ARG0=bdns
ARG1=${1:-void}


case $ARG1 in
	start|stop|void|detach)
		:
		;;
	*)
		ARG1=void
		;;
esac

[ ${ARG1:-void} = void ] && {

	[ -x /opt/phion/modules/box/boxsrv/${MODULENAME}/bin/bdns ] || exit 1
	/opt/phion/modules/box/boxsrv/${MODULENAME}/bin/bdns detach &>/dev/null &
	exit 0

}

function fEXIT {
	$logerror "Info" "${ARG0}[$$]: ------------ END --------------------"
}


function fTERM 
{
	trap '' TERM
	
	$logerror "Info" "${ARG0}[$$]: caught SIGTERM, cleaning up and exiting"
	local CSTATE=$(cat ${OPCONFFILE} 2>/dev/null); CSTATE=${CSTATE:-on}
	local PSTATE=$(cat ${STATEFILE} 2>/dev/null); PSTATE=${PSTATE:-on}

	setSTATE off

	[ -f /etc/resolv.conf.nbdns ] && /bin/ln -sf /etc/resolv.conf.nbdns /etc/resolv.conf
	[ -f ${NAMEDPIDFLE} ] && {
		 [[ $PSTATE = on ]] && {
			$RNDC stop
			sleep 1
		}
		rm -f ${NAMEDPIDFLE}
	}
	[[ -f ${RUNDIR}/bdns0.pid ]] && rm -f ${RUNDIR}/bdns0.pid
	exit 0
}

function fALRM
{
	trap '' ALRM
	$logerror "Info" "${ARG0}[$$]: caught SIGALRM signal, re-reading configuration"
	RUN=1
	#[ -f ${OPCONFFILE} ] && source ${OPCONFFILE}

	trap fALRM ALRM
	
}

function restartNAMED {

	local OPID
	
	
	[ ! -L /usr/sbin/bdns ] && /bin/ln -sf /usr/sbin/named /usr/sbin/bdns

	[ -f ${NAMEDPIDFLE}  ] && {           # syslog-ng pid
		OPID=$(cat ${NAMEDPIDFLE} 2>/dev/null)
		ps ww ${OPID:-0} | grep bdns && {
			$RNDC reconfig &>/dev/null
			$logerror "Info" "${ARG0}[$$]: active local DNS daemon process found as pid=${OPID}, reloaded configuration"
			return 1
		}
		rm -f ${NAMEDPIDFLE} &>/dev/null
	}	

	sleep 1

	chmod 666 /dev/random
	$logerror "Info" "${ARG0}[$$]: no active local DNS daemon process found, starting local DNS daemon process"
	/usr/sbin/bdns -4 -f -c ${OPCONFDIR}/named.conf -u ${RUNAS} &>/dev/null &
	return 0

}


##############  check if already running  ###################################

# if another process is already running then kill yourself cf  -> void) option below


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

trap fEXIT EXIT
$logerror "Info" "${ARG0}[$$]: ----------- START -------------------"


trap '' ALRM USR1 INT PIPE HUP BUS

[ -f /etc/rndc.conf ] && rm -f /etc/rndc.conf

if [ -s /etc/rndc.key ]; then 
	chown ${RUNAS}.${RUNAS} /etc/rndc.key
	chmod 600  /etc/rndc.key
else
	${RNDC}-confgen -a
	chown ${RUNAS}.${RUNAS} /etc/rndc.key
	chmod 600  /etc/rndc.key
fi




[ ! -d ${RUNDIR} ] && {
	mkdir -p ${RUNDIR}
	cp -af /opt/phion/modules/box/boxsrv/bdns/localhost.rev ${RUNDIR} 
	chown -R ${RUNAS}.${RUNAS} ${RUNDIR} 
}

[ ! -d ${OPCONFDIR} ] && {
	mkdir -p ${OPCONFDIR}
	[ -f ${RUNDIR}/named.conf ] && mv -f ${RUNDIR}/named.conf ${OPCONFDIR}/named.conf
}
chmod 755 ${OPCONFDIR}

[ ! -f ${RUNDIR}/localhost.rev ] &&  {
	cp -af /opt/phion/modules/box/boxsrv/bdns/localhost.rev ${RUNDIR}
	chown ${RUNAS}.${RUNAS} ${RUNDIR}/localhost.rev
}

SLVZONEDIR="${RUNDIR}/slavezones"
[[ ! -d ${SLVZONEDIR} ]] && {
	mkdir -p ${SLVZONEDIR}
	chown -R ${RUNAS}.${RUNAS} ${SLVZONEDIR}
	chmod 755 ${SLVZONEDIR}
}


STATUS=$(cat ${STATEFILE} 2>/dev/null); STATUS=${STATUS:-idle}


case $ARG1 in

	stop)
		
		if [ ${STATUS:-off} = off -o ${STATUS:-off} = idle ]; then
			: 
			$logerror "Notice" "${ARG0}[$$]: request=stop, status=${STATUS}, no action taken"
		else
			
			[ -f ${RUNDIR}/bdns0.pid ] && {
				OPID=$(cat ${RUNDIR}/bdns0.pid)
                        	ps ww ${OPID} | grep bdns && {
					[ ${STATUS:-off} = on -o $STATUS = idle ] && {
						kill -ALRM ${OPID}
						$logerror "Info" "${ARG0}[$$]: request=stop, status=${STATUS}, action=sent SIGALRM to pid ${OPID}"		

					}
				}
			}
		fi
		# if we haven't been off we are now idle!!
		exit 0
			
		;;
	start)
		$logerror "Info" "${ARG0}[$$]: request=start, status=$STATUS"
		# ignore when blocked, i.e. there is no running parent bdns job!!!
		# start when idle
		# ignore when already running except for a reload of the config file
		
		[ $STATUS = off ] && {

			[ -f /etc/resolv.conf.nbdns ] && {

				if ! diff --brief /etc/resolv.conf.nbdns /etc/resolv.conf &>/dev/null; then
					/bin/ln -sf /etc/resolv.conf.nbdns /etc/resolv.conf
					$logerror "Notice" "${ARG0}[$$]: request=start, status=${STATUS}, action=relink /etc/resolv.conf to /etc/resolv.conf.nbdns"
					[ -d /var/phion/chroot/etc_resolv.conf ] && {
						set +f
						for L in /var/phion/chroot/etc_resolv.conf/*; do
							cp -f /etc/resolv.conf $L
						done
						set -f
					}
				fi
			}
		} 

		
		
		[ -f ${RUNDIR}/bdns0.pid ] && {
			OPID=$(cat ${RUNDIR}/bdns0.pid)
                        ps ww ${OPID} | grep bdns && {
				[ ${STATUS:-off} = on -o $STATUS = idle ] && {
					kill -ALRM ${OPID}
					$logerror "Info" "${ARG0}[$$]: request=start, status=${STATUS}, action=sent SIGALRM to pid ${OPID}"		
					
				}
			}
		}
		exit 0	
		;;
	detach)
		
		[ -f ${RUNDIR}/bdns0.pid ] && {
			OPID=$(cat ${RUNDIR}/bdns0.pid)
                	ps ww ${OPID:-0} | grep bdns &>/dev/null && exit 1 
		}
		;;
esac
		


trap fTERM TERM
trap fALRM ALRM


arr=($(echo "${MYLOGFLE}" | tr "_" "\n"))

$SYSLOGATTACH -m ${MODULENAME} -n ${arr[1]} -t ${arr[2]} -p "^bdns"


CSTATE=off
[ -f ${OPCONFFILE} ] && CSTATE=$(/bin/cat ${OPCONFFILE})
CSTATE=${CSTATE:-off}


[ -f /etc/resolv.conf.wbdns -a ${CSTATE:-off} = on ] && {
	if ! diff --brief /etc/resolv.conf.wbdns /etc/resolv.conf &>/dev/null; then
		/bin/ln -sf /etc/resolv.conf.wbdns /etc/resolv.conf
		$logerror "Notice" "${ARG0}[$$]: resolv.conf has changed, action=relink /etc/resolv.conf to /etc/resolv.conf.wbdns"
		[ -d /var/phion/chroot/etc_resolv.conf ] && {
			set +f
			for L in /var/phion/chroot/etc_resolv.conf/*; do
				cp -f /etc/resolv.conf $L
			done
			set -f
		}
	fi
}
		
[ -f /etc/resolv.conf.nbdns -a ${CSTATE:-off} = off ] && {
	if ! diff --brief /etc/resolv.conf.nbdns /etc/resolv.conf &>/dev/null; then
		/bin/ln -sf /etc/resolv.conf.nbdns /etc/resolv.conf
		$logerror "Notice" "${ARG0}[$$]: resolv.conf has changed, action=relink /etc/resolv.conf to /etc/resolv.conf.nbdns"
		[ -d /var/phion/chroot/etc_resolv.conf ] && {
			set +f
			for L in /var/phion/chroot/etc_resolv.conf/*; do
				cp -f /etc/resolv.conf $L
			done
			set -f
		}
	fi
}

echo $$ > ${RUNDIR}/bdns0.pid

[ ${CSTATE:-off} != off ] && {

	[ ! -L /usr/sbin/bdns ] && /bin/ln -sf /usr/sbin/named /usr/sbin/bdns
	[ -x /usr/sbin/named ] && {
		setSTATE on
		MYSTATE=on
		$logerror "Info" "${ARG0}[$$]: starting local DNS daemon process"
		
		touch ${NAMEDPIDFLE}; chown nobody.nobody ${NAMEDPIDFLE}; chmod 644 ${NAMEDPIDFLE}
		
		/usr/sbin/bdns -4 -f -c ${OPCONFDIR}/named.conf -u ${RUNAS} &>/dev/null &
		echo $! > ${NAMEDPIDFLE}
		sleep 2
	}
}


[ ${CSTATE:-off} = off ] && {
	MYSTATE=idle
	setSTATE idle
}

while true; do
	sleep 1
	
	# TODO job monitor for bdns
	
	[ ${RUN} = 0 ] && {
		[ ${CSTATE:-off} = on ] && {
		
			[ ! -L /usr/sbin/bdns ] && /bin/ln -sf /usr/sbin/named /usr/sbin/bdns

			#TODO needs to be improved a little here
			if [ -f ${NAMEDPIDFLE}  ] ; then
				OPID=$(cat ${NAMEDPIDFLE} 2>/dev/null)
				ps ww ${OPID:-0} | grep bdns || {
					$logerror "Info" "${ARG0}[$$]: no active local DNS daemon process found, starting local DNS daemon process"
					/usr/sbin/bdns -4 -f -c ${OPCONFDIR}/named.conf -u ${RUNAS} &>/dev/null &
					setSTATE on

				}
			else
				PIDS=$(pidof -o %PPID bdns)
				for i in ${PIDS}; do
					[[ _${i} = _${MYPID} ]] && continue
					ps ww ${i:-0} | grep bdns &>/dev/null && {
						kill -KILL ${i}
						$logerror "Info" "${ARG0}[$$]: sent SIGKILL to spurious local DNS daemon process, pid=${i}"
					}
				done
				$logerror "Info" "${ARG0}[$$]: no active local DNS daemon process found, starting local DNS daemon process"
				/usr/sbin/bdns -4 -f -c ${OPCONFDIR}/named.conf -u ${RUNAS} &>/dev/null &
				setSTATE on
				
			fi			
			
		}
		[ ${CSTATE:-off} = off ] && {
		
			[ ! -L /usr/sbin/bdns ] && /bin/ln -sf /usr/sbin/named /usr/sbin/bdns

			#TODO needs to be improved a little here
			[ -f ${NAMEDPIDFLE}  ] && {           # syslog-ng pid
				OPID=$(cat ${NAMEDPIDFLE} 2>/dev/null)
				ps ww ${OPID:-0} | grep bdns &&  {
					$logerror "Notice" "${ARG0}[$$]: active local DNS daemon process found as pid=${OPID}, action=terminate local DNS daemon"
					$RNDC stop
					setSTATE idle
				}
			}
		}
		
	}
	
	
	
	sleep 1
	[ $RUN = 1 ] && {
		RUN=0
		CSTATE=$(/bin/cat ${OPCONFFILE})
		[ ${CSTATE:-off} = on ] && { 	
			restartNAMED
			setSTATE on
			MYSTATE=on
			
			[ -f /etc/resolv.conf.wbdns -a ${CSTATE:-off} = on ] && {
				if ! diff --brief /etc/resolv.conf.wbdns /etc/resolv.conf &>/dev/null; then
					/bin/ln -sf /etc/resolv.conf.wbdns /etc/resolv.conf
					$logerror "Notice" "${ARG0}[$$]: resolv.conf has changed, action=relink /etc/resolv.conf to /etc/resolv.conf.wbdns"
					[ -d /var/phion/chroot/etc_resolv.conf ] && {
						set +f
						for L in /var/phion/chroot/etc_resolv.conf/*; do
							cp -f /etc/resolv.conf $L
						done
						set -f
					}
				fi
			}
			sleep 1
			$RNDC flush
		}
		[ ${CSTATE:-off} = off ] && { 	
		
			if [ -f ${RUNDIR}/bdns.pid ]; then
				OPID=$(cat ${RUNDIR}/bdns.pid)
				ps ww ${OPID:-0} | grep bdns && {
					[ -f /etc/resolv.conf.nbdns ] && {
						if ! diff --brief /etc/resolv.conf.nbdns /etc/resolv.conf &>/dev/null; then
							/bin/ln -sf /etc/resolv.conf.nbdns /etc/resolv.conf
							$logerror "Notice" "${ARG0}[$$]: resolv.conf has changed, action=relink /etc/resolv.conf to /etc/resolv.conf.nbdns"
							[ -d /var/phion/chroot/etc_resolv.conf ] && {
								set +f
								for L in /var/phion/chroot/etc_resolv.conf/*; do
									cp -f /etc/resolv.conf $L
								done
								set -f
							}
						fi
					}
					$logerror "Notice" "${ARG0}[$$]: active local DNS daemon process found as pid=${OPID}, action=terminate local DNS daemon"
					$RNDC stop
					setSTATE idle
				}
			else
				#TODO universal kill a la OSPF
 				setSTATE idle
			fi
		}
		
	}	
done

$logerror "Fatal" "${ARG0}[$$]: abnormal termination beyond main worker loop"
setSTATE off
exit 1
