#!/bin/bash2

# UpdateDynDNS
# routine used to update dynamic DNS @ dyndns.org
# author k.gheri@phion.com
# Copyright phion IT GmbH, 2003-2007  phion AG 2007-2009
#

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

PMODPATH="/opt/phion/modules/box/boxnet"
[ -f ${PMODPATH}/moddefs.conf ] && source ${PMODPATH}/moddefs.conf
LFLEKEY=logfile_${1}
MYLOGFLE="${!LFLEKEY:-"box_Network_dyndns"}"


DYNDNSDIR=/var/phion/run/boxnet/DNS
DYNDNSMEM=/var/phion/preserve/boxnet/DNS

[[ -d ${DYNDNSMEM} ]] || mkdir -p ${DYNDNSMEM}

LOGGER="$(which logger)"


[ ! -x $LOGGER ] && [ -x /bin/logger ] && eval LOGGER=/bin/logger

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

PREFIX=""
H=1
for ((k=1 ; H-k ; k++)); do
    PREFIX="${PREFIX} $(SUB)"
done
export H=$H

ARG0="UpdateDynDNS"
ARGB="UpdateDynDNS"
ARGS=""

DATE=$(which date)
#
# still requires log output and event in case of problems
#

$logerror "Info" "[0140100] ${ARG0}[$$]: START, dynamic DNS update"

function fEXIT {

	[[ -f ${TMPANAME} ]] && rm -f ${TMPANAME}
	[[ -f ${TMPFNAME} ]] && rm -f ${TMPFNAME}

}



LYNX="$(which lynx)"
[ -x ${LYNX} ] || {
	$logerror "Error" "[0140100] ${ARG0}[$$]: END, missing utility file $(MARK ${LYNX}), aborting"
	exit 1 
}


[ $# -lt 2 ] && {
	$logerror "Error" "[0140100] ${ARG0}[$$]: END, too few arguments $(MARK $@), aborting"
	exit 2
}
USER=""
PASSWD=""
HNAME=""
WCARD="OFF"
MX=""
BMX="NO"

MYIP=${2}
NAMELINK=${1}
STANDOFF=""
SYSTEM="dyndns"

HOSTBIN=$(which host)
GREP=$(which grep)


if [ -f /etc/ppp/dyndns.$NAMELINK ]; then
	source /etc/ppp/dyndns.$NAMELINK
else
	$logerror "Error" "[0140100] ${ARG0}[$$]: END, no /etc/ppp/dyndns.$NAMELINK found, aborting"
	exit 0
fi


# LI LO sanity check - begin 

MYNAME=$(basename ${0})
ps ax -o pid= -o cmd= | grep ${MYNAME} | grep -v grep > /tmp/dyndns_ps.txt

while read LINE; do
	set -- $LINE
	if [[ _${1} != _$$ ]]; then
		kill -TERM ${1} &>/dev/null
		TMP=$(ps ax -o pid= -o cmd= | grep ${1})
		if [[ $? -eq 0 ]]; then
			kill -9 ${1} &>/dev/null
		fi
	fi
done < /tmp/dyndns_ps.txt

rm -f /tmp/dyndns_ps.txt

# LI LO sanity check - end


: ${FAIRUSE:=40320}		# timespan of 28 days in units of minutes = 2419200 [s]
let FAIRUSE+=61			# 61 mins reserve

: ${STANDOFF:=30}
FNAME=${DYNDNSDIR}/dyndns.lastip.${NAMELINK}
TMPFNAME=${DYNDNSDIR}/dyndns.lastip.${NAMELINK}.$$.tmp
ANAME=${DYNDNSMEM}/dyndns.lastattribute.${NAMELINK}
TMPANAME=${DYNDNSDIR}/dyndns.lastattribute.${NAMELINK}.$$.tmp



###################################################################################
# need to check reordering of dynamic adapters
# assume boxnet writes a file dynlinknames in /var/phion/preserve/boxnet containing the NAMELINK to section name assignments
# its structure is as follows: 
#	LINKNAME_<linkname>=<type>_<sectionname>
#	SECTNAME_<type>_<sectionname>=<linkname>
#	interface name follows from <type> and <linkname>


[[ -f /var/phion/preserve/boxnet/dynlinknames ]] && {
	source /var/phion/preserve/boxnet/dynlinknames 
	eval  OUT=\$${LINKNAME_${LINKNAME}}; set -- ${OUT//_/ }
	MYTYPE=${1:-unknown}; MYNAME=${2:-unknown}
	$logerror "Info" "[0140100] ${ARG0}[$$]: handling dynamic link ${LINKNAME} of type ${MYTYPE} and link name ${MYNAME:-first}" 

	FNAME=${DYNDNSDIR}/dyndns.lastip."${OUT}"
	TMPFNAME=${DYNDNSDIR}/dyndns.lastip."${OUT}".$$.tmp
	ANAME=${DYNDNSMEM}/dyndns.lastattribute."${OUT}"
	TMPANAME=${DYNDNSDIR}/dyndns.lastattribute."${OUT}".$$.tmp
	
	
	# legacy and migration statement required at time of integration in 4.2
	[[ -f ${DYNDNSDIR}/dyndns.lastip.${LINKNAME} ]] && mv -f ${DYNDNSDIR}/dyndns.lastip.${LINKNAME} ${DYNDNSDIR}/dyndns.lastip."${OUT}"
	
	
}

trap fEXIT EXIT TERM

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



#TODO BOOTSTRAP!!
#FNAME=/etc/ppp/dyndns.lastip.${NAMELINK}  #is stamped by UpdateDynDNS itself






LIP="0.0.0.0"
DELTAT=${FAIRUSE}
[[ -f ${FNAME} ]] &&  {
	DELTAT=$($DATE +%s); P_LAST=${DELTAT} 
	source ${FNAME}
	LIP=${P_IP}
	let DELTAT-=P_LAST; let DELTAT/=60 
	[[ $DELTAT -lt 0 ]] && DELTA=${FAIRUSE}
}

ATTRCHGD=0
if [[ -f ${ANAME} ]]; then
	source ${ANAME}
	
	[[ _${HNAME} != _${P_HNAME} ]] && ATTRCHGD=1 
	[[ _${WCARD} != _${P_WCARD} ]] && ATTRCHGD=1 
	[[ _${MX} != _${P_MX} ]] && ATTRCHGD=1
	[[ _${BMX} != _${P_BMX} ]] && ATTRCHGD=1 
	[[ _${SYSTEM} != _${P_SYSTEM} ]] && ATTRCHGD=1 

	
	[[ ${ATTRCHGD} = 1 ]] && {
		$logerror "Notice" "[0142011] ${ARG0}[$$]: dynamic DNS attributes have changed, hostname ${P_HNAME:-not-set-} -> ${HNAME}, wildcard ${P_WCARD} -> ${WCARD}, mx ${P_MX} -> ${MX}, backupmx ${P_BMX} -> ${BMX}, system ${P_SYSTEM} -> ${SYSTEM}"
	}		
else
	ATTRCHGD=2
fi

# check for time elapsed since last update
TIMEOK=0
[[ $DELTAT -ge ${FAIRUSE} ]] &&  {
	TIMEOK=1
}	
{
	OUT=${DELTAT}
	TMPDAYS=$((OUT/1440))
	OUT=$((OUT-1440*TMPDAYS)); TMPHOURS=$((OUT/60))
	TMPMINS=$((OUT-TMPHOURS*60)) 
	$logerror "Info" "[0142013] ${ARG0}[$$]: last update occurred ${TMPDAYS} days ${TMPHOURS} hours ${TMPMINS} minutes ago"
}

# check for known record
RECFD=0
OUT=$(${HOSTBIN} -W 5 ${HNAME} | ${GREP} -c "${MYIP:-0.0.0.0}\$" 2>/dev/null)
[[ ${OUT:-0} -gt 0 ]] && {
	RECFD=1
	$logerror "Info" "[0142012] ${ARG0}[$$]: hostname ${HNAME} already resolves to ${MYIP}"
}

# check for believed IP change
IPCHGD=0
[[ ${RECFD:-0} = 0 ]] && {
	[ _${MYIP} != _${P_IP} -o $LIP = 0.0.0.0 ] && {
		IPCHGD=1
		$logerror "Info" "[0142011] ${ARG0}[$$]: local IP has changed ${P_IP} -> ${MYIP}"  
	}
}

# decision tree
DOIT=0
if [[ ${ATTRCHGD:-0} -ge 1 ]]; then 
	# attributes have changed, will have to update regardless of IP change and elapsed time
	DOIT=1
	$logerror "Info" "[0142010] ${ARG0}[$$]: update will be triggered because of a change of operational DynDNS attributes"

elif [[ ${RECFD:-0} = 0 ]]; then
	
	if [[ ${IPCHGD} = 1 ]]; then
		DOIT=1
		$logerror "Info" "[0142010] ${ARG0}[$$]: update will be triggered because of a change of IP address, no confirmation from name query available"
	else
		if  [[ ${TIMEOK} = 1 ]]; then 
			DOIT=1
			$logerror "Info" "[0142010] ${ARG0}[$$]: update will be triggered because standoff time has been exceeed, no confirmation from name query available, no indication that IP has changed available"
		else
			$logerror "Info" "[0140100] ${ARG0}[$$]: END, no need to update, exiting"
			exit 0
		fi
	fi

elif [[ ${RECFD:-0} = 1 ]]; then
	if  [[ ${TIMEOK} = 1 ]]; then 
		DOIT=1
		$logerror "Info" "[0142010] ${ARG0}[$$]: update will be triggered because standoff time has been exceeed, confirmation from name query is available"
	else
		$logerror "Info" "[0140100] ${ARG0}[$$]: END, no need to update, exiting"
		exit 0
	fi		
fi




[ -z $USER -o -z $PASSWD -o -z ${HNAME} ] && {
	$logerror "Error" "[0142006] ${ARG0}[$$]: END, dynamic update with ${MYIP} for ${HNAME} aborted due to incomplete authorization information"
	$LOGGER -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=2;class_name=${ARGB};type_id=58;type_name=${HNAME};data=dynamic address registration of ${MYIP} as ${HNAME} aborted due to incomplete authorization information"
	exit 3
}


RET=""
OUT="" 
Ta=0 
Tb=0


APPEND=""
[ _$MX != _ ] && {
	APPEND="&mx=${MX}&backmx=${BMX:-NO}"
}

CMD="${LYNX} -dump -auth=${USER}:${PASSWD} \"${HTTP:-http}://members.dyndns.org/nic/update?system=${SYSTEM}&hostname=${HNAME}&myip=${MYIP}\
&wildcard=${WCARD:-OFF}${APPEND}\" 2>&1"




while true; do


	$logerror "Info" "[0142003] ${ARG0}[$$]: dynamic DNS update request system=${SYSTEM}&hostname=${HNAME}&myip=${MYIP}&wildcard=${WCARD:-OFF}${APPEND}"
	Ta=$(date +%s)
	OUT=$(${LYNX} -dump -auth=${USER}:${PASSWD} "${HTTP:-http}://members.dyndns.org/nic/update?system=${SYSTEM}&hostname=${HNAME}&myip=${MYIP}&wildcard=${WCARD:-OFF}${APPEND}" 2>&1)
	RET=$?
	
	set -- ${OUT}
	
	if [ $RET = 0 ]; then
		#[ _"${1}" = _"good" -a _"${2}" = _"${MYIP}" ] && {
		[ _"${1}" = _"good"  ] && {
		
			$logerror "Notice" "[0142004] ${ARG0}[$$]: dynamic DNS update with ${MYIP} for ${HNAME} succeeded with dyndns.org, server returned ${OUT}"
			$LOGGER -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=2;class_name=${ARGB};type_id=57;type_name=${HNAME};data=dynamic address ${MYIP} registered as ${HNAME}"
		
		
			{ 
				echo P_IP=${MYIP} 
				echo P_HNAME=${HNAME}
				echo P_WCARD=${WCARD}
				echo P_MX=${MX}
				echo P_BMX=${BMX}
				echo P_SYSTEM=${SYSTEM}
				echo P_LAST=$($DATE +%s)
			} > ${TMPFNAME}
			
			mv -f ${TMPFNAME} ${FNAME}
			$logerror "Notice" "[0142004] ${ARG0}[$$]: wrote current IP and update stamp to ${FNAME}"
			
			{ 
				echo P_HNAME=${HNAME}
				echo P_WCARD=${WCARD}
				echo P_MX=${MX}
				echo P_BMX=${BMX}
				echo P_SYSTEM=${SYSTEM}
			} > ${TMPANAME}
			
			if [[ -f ${ANAME} ]]; then 
				if ! MoveOrDelOnDiff ${TMPANAME} ${ANAME} &>/dev/null; then
					$logerror "Notice" "[0142004] ${ARG0}[$$]: wrote changed dynamic DNS attributes to ${ANAME}"
				fi
			else
				mv -f ${TMPANAME} ${ANAME} &>/dev/null
				$logerror "Notice" "[0142004] ${ARG0}[$$]: wrote changed dynamic DNS attributes to ${ANAME}"
			fi
			$logerror "Info" "[0140100] ${ARG0}[$$]: END, exiting successfully"
			exit 0
		}
		[ _"${1}" = _badauth ] && {
			$logerror "Warning" "[0142007] ${ARG0}[$$]: END, dynamic DNS update with ${MYIP} for ${HNAME} refused by dyndns.org: ${OUT}"
			$LOGGER -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=2;class_name=${ARGB};type_id=58;type_name=${HNAME};data=dynamic address ${MYIP}  not registered as ${HNAME}: ${OUT}"
			exit 0
		}
		
		[ _"${1}" = _nochg ] && {
			$logerror "Warning" "[0142007] ${ARG0}[$$]: END, dynamic DNS update with ${MYIP} for ${HNAME} refused by dyndns.org: ${OUT}"
			exit 0
		}
	else
	
	#[ ${RET:-0} != 0 ] && {
	
		[ _"${2}" = _"${MYIP}" ] && {
			{ 
				echo P_IP=${MYIP} 
				echo P_HNAME=${HNAME}
				echo P_WCARD=${WCARD}
				echo P_MX=${MX}
				echo P_BMX=${BMX}
				echo P_SYSTEM=${SYSTEM}
				echo P_LAST=$($DATE +%s)
			} > ${TMPFNAME}
			
			mv -f ${TMPFNAME} ${FNAME}
			$logerror "Notice" "[0142004] ${ARG0}[$$]: wrote current IP and update stamp to ${FNAME}"
			{ 
				echo P_HNAME=${HNAME}
				echo P_WCARD=${WCARD}
				echo P_MX=${MX}
				echo P_BMX=${BMX}
				echo P_SYSTEM=${SYSTEM}
			} > ${TMPANAME}
			
			if [[ -f ${ANAME} ]]; then 
				if ! MoveOrDelOnDiff ${TMPANAME} ${ANAME} &>/dev/null; then
					$logerror "Notice" "[0142004] ${ARG0}[$$]: wrote changed dynamic DNS attributes to ${ANAME}"
				fi
			else
				mv -f ${TMPANAME} ${ANAME} &>/dev/null
				$logerror "Notice" "[0142004] ${ARG0}[$$]: wrote changed dynamic DNS attributes to ${ANAME}"
			fi
		}
			
		[ _"${1}" = _badauth ] && {
			$logerror "Warning" "[0142007] ${ARG0}[$$]: END, dynamic DNS update with ${MYIP} for ${HNAME} refused by dyndns.org: ${OUT}"
			$LOGGER -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=2;class_name=${ARGB};type_id=58;type_name=${HNAME};data=dynamic address ${MYIP}  not registered as ${HNAME}: ${OUT}"
			exit 0
		}
	
	
		[ _"${1}" = _nochg ] && {
			$logerror "Warning" "[0142007] ${ARG0}[$$]: END, dynamic DNS update with ${MYIP} for ${HNAME} refused by dyndns.org: ${OUT}"
			exit 0
		}
	fi
	
	
	$logerror "Error" "[0142005] ${ARG0}[$$]: dynamic DNS update with ${MYIP} for ${HNAME} failed: ${OUT}"
	$LOGGER -i -puucp.info -tEvent "layer_id=1;layer_name=network layer;class_id=2;class_name=${ARGB};type_id=58;type_name=${HNAME};data=dynamic address ${MYIP}  not registered as ${HNAME}: ${OUT}"
	
	Tb=$(date +%s)
	let Tb=Tb-Ta
	Tb=$(((STANDOFF*60)-Tb))	
	for ((i=0;Tb-i;i++)); do
		sleep 1
	done
	
done


$logerror "Info" "[0140100] ${ARG0}[$$]: END, exiting"
