#!/bin/bash
if [[ "$1" == 'debug'  ]]; then set -x;		_DEBUG=$1; shift; fi
if [[ "$1" == 'debug2' ]]; then set -xvT;	_DEBUG=$1; shift; fi
if [[ "$1" == 'trace'  ]]; then 		_TRACE=$1; shift; fi
####################################################################
#  Watcher tool
# - MyFritzbox -
# 
# Determine current IP address of a FritzBox router
#-------------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. ../system.conf
. ../watchermap.conf
. ../common.conf
. ../common.bashlib
#-------------------------

OPTIND=1 
VERBOSE=0
while getopts v flag
do
	case "$flag" in
		v) VERBOSE=1
	;;
	esac
done
shift "$((OPTIND-1))"

#
# Determine current IP address of a FritzBox router
#
BOXID_FILE=/root/.BoxID

if [ -f $BOXID_FILE ]
then
	BOXID=`cat $BOXID_FILE`
else
	echo "You must provide your MyFritz address for the active router"
	echo "that you have registered on Myfritz.net (https://www.myfritz.net)/"
	echo "   <my router ID>.myfritz.net"
	echo "Set this on a single line in /root/.BoxID"
	echo " e.g.: 	ypjdiq75ksl@28.myfritz.net"
	echo "Change the rights to 600, owner 'root'"
	echo "Exiting ..."
	exit
fi

LOGFILE=$LOG_DIR/$ME
IP=`dig +short -4 $BOXID`

echo $IP > $LOGFILE


#---------------------
initial=0
if [ -f $LOGFILE ]
then read OLD_IP < $LOGFILE
else (( initial++ ))
fi

THIS_IP=`dig +short $DYN_ADDRESS`
THIS_HOST=`dig +short -x $THIS_IP`

#Stamp="`date +%Y-%m-%d_%T`"
Stamp="`date --iso=seconds`"
if [ $initial -gt 0 ]
then
	ipset -q -exist add myrouters $THIS_IP comment "$ME,initial, $Stamp"
	echo $THIS_IP > $LOG_DIR/DYN_IP
else		
	if [[ "$OLD_IP" =~ "$THIS_IP" ]]
	then	: ipset -q -exist add myrouters $THIS_IP comment "$ME,refreshed, $Stamp"
	else 
		echo $THIS_IP > $LOG_DIR/DYN_IP
		ipset -q -exist add myrouters $THIS_IP comment "$ME,changed, $Stamp"
		ipset -q -exist del myrouters $OLD_IP
		logger "$ME, Dyn IP address changed from '$OLD_IP' to '$THIS_IP'"
	fi
fi

echo $THIS_HOST > $LOG_DIR/DYN_POOLADDR

if [ $VERBOSE -ne 0 ]; then echo "$THIS_IP"; fi
