#!/bin/sh
#/usr/lib/ddnsmngr/ddnsmngr_updater.sh
#
# Distributed under the terms of the GNU General Public License (GPL) version 2.0
# Original written by Eric Paul Bishop, January 2008
# (Loosely) based on the script on the one posted by exobyte in the forums here:
# http://forum.openwrt.org/viewtopic.php?id=14040
# extended and partial rewritten
# 2014-2018 Christian Schoenebeck <christian.schoenebeck@gmail.com>
# 2024 Suvendhu Hansa <suvendhu.hansa@iopsys.eu>


. /usr/share/libubox/jshn.sh

if [ -f /usr/lib/ddns/dynamic_dns_functions.sh ]; then
	. /usr/lib/ddns/dynamic_dns_functions.sh
else
	echo "/usr/lib/ddns/dynamic_dns_functions.sh not found, may be ddns_script not installed"
	exit 0
fi

# shared authority parse/rebuild helpers (ddns_parse_authority, ddns_rebuild_url)
. /usr/lib/ddnsmngr/ddns_url_lib.sh

get_registered_ipaddr() {
	service="${1}"
	host="${2}"
	version="${3}"

	if [ -f /tmp/ddnsmngr/registered_host ]; then
		ip=$(cat /tmp/ddnsmngr/registered_host | eval grep \"$service $host $version\" | cut -d' ' -f 4)
		if [ -n "${ip}" ]; then
			eval "$4=\"$ip\""
			return 0
		fi
	fi

	eval "$4=\"\""
	return 0
}

start_ddns_client() {
	json_select $1
	if [ "$?" -ne 0 ]; then
		return
	fi

	json_get_var intf interface
	json_get_var serv service_name
	json_get_var user username
	json_get_var pass password
	json_get_var host lookup_host
	json_get_var netw ip_network
	json_get_var file proc_info_file
	json_get_var v6_enable use_ipv6
	json_get_var force_enable force_ipversion
	json_get_var https_enable use_https
	json_get_var dns_tcp force_dnstcp
	json_get_var srv_addr server_address
	json_get_var srv_port server_port
	json_get_var proto protocol
	json_get_var chk_intv check_interval
	json_get_var rty_intv retry_interval
	json_get_var max_rty max_retries
	json_select ..

	OBJ="{ \"interface\": \"${intf}\", \"service_name\": \"${serv}\", \"username\": \"${user}\", \
	\"password\": \"${pass}\", \"lookup_host\": \"${host}\", \"ip_network\": \"${netw}\", \
	\"proc_info_file\": \"${file}\", \"use_ipv6\": \"${v6_enable}\", \"force_ipversion\": \"${force_enable}\", \
	\"use_https\": \"${https_enable}\", \"force_dnstcp\": \"${dns_tcp}\", \
	\"server_address\": \"${srv_addr}\", \"server_port\": \"${srv_port}\", \"protocol\": \"${proto}\", \
	\"check_interval\": \"${chk_intv}\", \"retry_interval\": \"${rty_intv}\", \"max_retries\": \"${max_rty}\" }"

	# spawn the instance
	/usr/lib/ddnsmngr/ddnsmngr_updater.sh -v 0 -o "${OBJ}" -- start &
}

start_daemon_for_all_hosts() {
	mkdir -p /tmp/ddnsmngr
	touch /tmp/ddnsmngr/registered_host

	if [ -f "${CONFIG}" ]; then
		json_load_file "${CONFIG}"

		if json_is_a services array; then
			json_select services
			if [ "$?" -eq 0 ]; then
				idx=1
				while json_is_a ${idx} object
				do
					start_ddns_client ${idx}
					idx=$(( idx + 1 ))
				done

			fi
		fi
	fi
}

stop_daemon_for_all_hosts() {
	if [ -f "${CONFIG}" ]; then
		json_load_file "${CONFIG}"

		if json_is_a services array; then
			json_select services
			if [ "$?" -ne 0 ]; then
				return
			fi

			idx=1
			while json_is_a ${idx} object
			do
				json_select ${idx}
				if [ "$?" -ne 0 ]; then
					continue
				fi

				json_get_var proc_file proc_info_file
				json_select ..
				idx=$(( idx + 1 ))

				if [ -n "${proc_file}" ]; then
					stop_section_processes "$proc_file"
				fi
			done
		fi
	fi
}

usage() {
	cat << EOF

Usage:
 $MYPROG [options] -- command

Commands:
start                Start all clients
stop                 Stop all clients

Parameters:
 -c CONFIG           Start/Stop all clients in config file
 -o OBJECT           OBJECT to start

 -h                  show this help and exit
 -V                  show version and exit
 -v LEVEL            VERBOSE=LEVEL (default 1)
                        '0' NO output to console
                        '1' output to console
                        '2' output to console AND logfile
                            + run once WITHOUT retry on error
 -d                  dry run (don't send any changes)

EOF
}

usage_err() {
	printf %s\\n "$MYPROG: $@" >&2
	usage >&2
	exit 1
}

while getopts ":hv:dc:o:V" OPT; do
	case "$OPT" in
		h)	usage; exit 0;;
		v)	VERBOSE=$OPTARG;;
		d)	DRY_RUN=1;;
		c)	CONFIG=$OPTARG;;
		o)	OBJECT=$OPTARG;;
		V)	printf %s\\n "ddns-scripts $VERSION"; exit 0;;
		:)	usage_err "option -$OPTARG missing argument";;
		\?)	usage_err "invalid option -$OPTARG";;
		*)	usage_err "unhandled option -$OPT $OPTARG";;
	esac
done
shift $((OPTIND - 1 ))	# OPTIND is 1 based

[ -n "$CONFIG" -a -n "$OBJECT" ] && usage_err "use either option '-c' or '-o' not both"
[ $# -eq 0 ] && usage_err "missing command"
[ $# -gt 1 ] && usage_err "to much commands"

case "$1" in
	start)
		if [ -z "$OBJECT" ]; then
			start_daemon_for_all_hosts
			exit 0
		fi
		;;
	stop)
		stop_daemon_for_all_hosts
		exit 0
		;;
	*)	usage_err "unknown command - $1";;
esac


# Global configuration settings
upd_privateip=$(uci -q get ddnsmngr.global.upd_privateip) || upd_privateip=0

# directory to store run informations
ddns_rundir=$(uci -q get ddnsmngr.global.ddns_rundir) || ddns_rundir="/var/run/ddnsmngr"
[ -d $ddns_rundir ] || mkdir -p -m755 $ddns_rundir

# directory to store log files
ddns_logdir=$(uci -q get ddnsmngr.global.ddns_logdir) || ddns_logdir="/var/log/ddnsmngr"
[ -d $ddns_logdir ] || mkdir -p -m755 $ddns_logdir

# number of lines to before rotate logfile
ddns_loglines=$(uci -q get ddnsmngr.global.ddns_loglines) || ddns_loglines=250
ddns_loglines=$((ddns_loglines + 1))

# format to show date information in log
ddns_dateformat=$(uci -q get ddnsmngr.global.ddns_dateformat) || ddns_dateformat="%F %R"
DATE_PROG="date +'$ddns_dateformat'"

# USE_CURL in place of WGET by do_transfer()
USE_CURL=$(uci -q get ddnsmngr.global.use_curl) || USE_CURL=0
[ -n "$CURL" ] || USE_CURL=0 # If curl not installed

# get all configured options in the json object
json_load "${OBJECT}"
json_get_var interface interface
json_get_var service_name service_name
json_get_var username username
json_get_var password password
json_get_var lookup_host lookup_host
json_get_var ip_network ip_network
json_get_var proc_info_file proc_info_file
json_get_var use_ipv6 use_ipv6
json_get_var force_ipversion force_ipversion
json_get_var use_https use_https
json_get_var force_dnstcp force_dnstcp
json_get_var server_address server_address
json_get_var server_port server_port
json_get_var protocol protocol
json_get_var check_interval check_interval
json_get_var retry_interval retry_interval
json_get_var max_retries max_retries

if [ -z "${proc_info_file}" ]; then
	echo "Exit process since option \"proc_info_file\" is Empty."
	exit 0
fi

# set file names
PIDFILE="$ddns_rundir/$proc_info_file.pid"	# Process ID file
UPDFILE="$ddns_rundir/$proc_info_file.update"	# last update successful send (system uptime)
DATFILE="$ddns_rundir/$proc_info_file.dat"	# save stdout data of WGet and other extern programs called
ERRFILE="$ddns_rundir/$proc_info_file.err"	# save stderr output of WGet and other extern programs called
IPFILE="$ddns_rundir/$proc_info_file.ip"	#
LOGFILE="$ddns_logdir/$proc_info_file.log"	# log file

# VERBOSE > 1 delete logfile if exist to create an empty one
# only with this data of this run for easier diagnostic
# new one created by write_log function
[ $VERBOSE -gt 1 -a -f $LOGFILE ] && rm -f $LOGFILE
# Previously -v 3 could we used for dry run
[ $VERBOSE -ge 3 ] && DRY_RUN=1

# TRAP handler
trap "trap_handler 0 \$?" 0	# handle script exit with exit status
trap "trap_handler 1"  1	# SIGHUP	Hangup / reload config
trap "trap_handler 2"  2	# SIGINT	Terminal interrupt
trap "trap_handler 3"  3	# SIGQUIT	Terminal quit
trap "trap_handler 15" 15	# SIGTERM	Termination

# set defaults
# MaxRetries: unset = global default; N (incl. 0) = exactly N retries (0 = none)
retry_max_count=${max_retries:-$(uci -q get ddnsmngr.global.default_max_retries || echo 100)}
RETRY_COUNT=0
use_syslog=2		# syslog "Notice"
use_logfile=1		# use logfile by default
ip_source="network"
is_glue=0		# default the ddns record is not a glue record

[ -z "$ip_network" -a $use_ipv6 -eq 0 ] && ip_network="wan"  # IPv4: default wan
[ -z "$ip_network" -a $use_ipv6 -eq 1 ] && ip_network="wan6" # IPv6: default wan6

# url encode username (might be email or something like this)
# and password (might have special chars for security reason)
[ -n "$username" ] && urlencode URL_USER "$username"
[ -n "$password" ] && urlencode URL_PASS "$password"

write_log 7 "************ ************** ************** **************"
write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
write_log 7 "ddns version  : $VERSION"
write_log 7 "instance configuration:${N}$(json_dump)"
case $VERBOSE in
	0) write_log  7 "verbose mode  : 0 - run normal, NO console output";;
	1) write_log  7 "verbose mode  : 1 - run normal, console mode";;
	2) write_log  7 "verbose mode  : 2 - run once, NO retry on error";;
	*) write_log 14 "error detecting VERBOSE '$VERBOSE'";;
esac
[ $DRY_RUN -ge 1 ] && write_log  7 "Dry Run: NOT sending update"

# determine what update url we're using if a service_name is supplied
# otherwise update_url is set inside configuration (custom update url)
# or update_script is set inside configuration (custom update script)
[ -n "$service_name" ] && {
	get_service_data "$service_name" "/etc/ddnsmngr/servers" update_url update_script UPD_ANSWER
}

# Apply Server authority overrides (ServerAddress/ServerPort/Protocol).
# Each override is empty when not set, in which case the value from the
# service file is kept. ddns_rebuild_url preserves userinfo and path/query.
[ -n "$update_url" ] && {
	case "$protocol" in
		https) o_https=1 ;;
		http)  o_https=0 ;;
		*)     o_https="" ;;
	esac
	update_url=$(ddns_rebuild_url "$update_url" "$o_https" "$server_address" "$server_port")
	# scheme is now final in update_url; if we forced it, stop send_update's
	# use_https upgrade from overriding our choice
	[ -n "$o_https" ] && use_https=0
}

[ -z "$update_url" -a -z "$update_script" ] && write_log 14 "No update_url found/defined or no update_script found/defined!"
[ -n "$update_script" -a ! -f "$update_script" ] && write_log 14 "Custom update_script not found!"

# without lookup host and possibly other required options we can do nothing for you
[ -z "$lookup_host" ] && write_log 14 "Host section not configured correctly! Missing 'lookup_host'"

domain="$lookup_host"

# verify validity of variables
[ -n "$lookup_host" ] && sanitize_variable lookup_host "$DNS_CHARSET" ""
[ -n "$domain" ] && sanitize_variable domain "$DNS_CHARSET_DOMAIN" ""

[ -n "$update_url" ] && {
	# only check if update_url is given, update_scripts have to check themselves
	[ -z "$domain" ] && $(echo "$update_url" | grep "\[DOMAIN\]" >/dev/null 2>&1) && \
		write_log 14 "Host section not configured correctly! Missing 'domain'"
	[ -z "$username" ] && $(echo "$update_url" | grep "\[USERNAME\]" >/dev/null 2>&1) && \
		write_log 14 "Service section not configured correctly! Missing 'username'"
	[ -z "$password" ] && $(echo "$update_url" | grep "\[PASSWORD\]" >/dev/null 2>&1) && \
		write_log 14 "Service section not configured correctly! Missing 'password'"
}

# set update intervals
# CheckInterval and RetryInterval are independent, each with its own floor.
# The floor is configurable in the global section and is also the value the
# data model returns when the per-server option is unset.
CHECK_FLOOR=$(uci -q get ddnsmngr.global.min_check_interval) || CHECK_FLOOR=300	# 5 min
RETRY_FLOOR=$(uci -q get ddnsmngr.global.min_retry_interval) || RETRY_FLOOR=60	# 1 min

# unset = current behaviour (10 min); a DM-set value is floored
CHECK_SECONDS=${check_interval:-600}
[ "$CHECK_SECONDS" -lt "$CHECK_FLOOR" ] && CHECK_SECONDS=$CHECK_FLOOR

FORCE_SECONDS=259200 # 3 days

RETRY_SECONDS=60 # 1 min - wait between retries when no valid local IP yet
# unset = current behaviour (retries waited one check interval = 600); a DM-set value is floored
RETRY_UPDATE_SECONDS=${retry_interval:-600}
[ "$RETRY_UPDATE_SECONDS" -lt "$RETRY_FLOOR" ] && RETRY_UPDATE_SECONDS=$RETRY_FLOOR

write_log 7 "check interval: $CHECK_SECONDS seconds"
write_log 7 "force interval: $FORCE_SECONDS seconds"
write_log 7 "retry interval: $RETRY_UPDATE_SECONDS seconds"
write_log 7 "retry max count : $retry_max_count times"

# kill old process if it exists & set new pid file
stop_section_processes "$proc_info_file"
[ $? -gt 0 ] && write_log 7 "'SIGTERM' was send to old process" || write_log 7 "No old process"
echo $$ > $PIDFILE

# determine when the last update was
# the following lines should prevent multiple updates if hotplug fires multiple startups
# as described in Ticket #7820, but did not function if never an update take place
# i.e. after a reboot (/var is linked to /tmp)
# using uptime as reference because date might not be updated via NTP client
get_uptime CURR_TIME
[ -e "$UPDFILE" ] && {
	LAST_TIME=$(cat $UPDFILE)
	# check also LAST > CURR because link of /var/run to /tmp might be removed
	# i.e. boxes with larger filesystems
	[ -z "$LAST_TIME" ] && LAST_TIME=0
	[ $LAST_TIME -gt $CURR_TIME ] && LAST_TIME=0
}
if [ $LAST_TIME -eq 0 ]; then
	write_log 7 "last update: never"
else
	EPOCH_TIME=$(( $(date +%s) - $CURR_TIME + $LAST_TIME ))
	EPOCH_TIME="date -d @$EPOCH_TIME +'$ddns_dateformat'"
	write_log 7 "last update: $(eval $EPOCH_TIME)"
fi

# let's check if there is already an IP registered on the web
get_registered_ipaddr $service_name $lookup_host $use_ipv6 REGISTERED_IP

# on IPv6 we use expanded version to be shure when comparing
[ $use_ipv6 -eq 1 ] && expand_ipv6 "$REGISTERED_IP" REGISTERED_IP

# loop endlessly, checking ip every check_interval and forcing an updating once every force_interval
write_log 6 "Starting main loop at $(eval $DATE_PROG)"
while : ; do

	get_current_ip CURRENT_IP		# read current IP
	[ $use_ipv6 -eq 1 ] && expand_ipv6 "$CURRENT_IP" CURRENT_IP	# on IPv6 we use expanded version

	if [ "$CURRENT_IP" = "invalid" ]; then
		sleep $RETRY_SECONDS &
		PID_SLEEP=$!
		wait $PID_SLEEP	# enable trap-handler
		PID_SLEEP=0
		continue
	fi

	# prepare update
	# never updated or forced immediate then NEXT_TIME = 0
	[ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
		&& NEXT_TIME=0 \
		|| NEXT_TIME=$(( $LAST_TIME + $FORCE_SECONDS ))

	get_uptime CURR_TIME		# get current uptime

	# send update when current time > next time or current ip different from registered ip
	if [ $CURR_TIME -ge $NEXT_TIME -o "$CURRENT_IP" != "$REGISTERED_IP" ]; then
		if [ $DRY_RUN -ge 1 ]; then
			write_log 7 "Dry Run: NO UPDATE send"
		elif [ "$CURRENT_IP" != "$REGISTERED_IP" ]; then
			write_log 7 "Update needed - L: '$CURRENT_IP' <> R: '$REGISTERED_IP'"
		else
			write_log 7 "Forced Update - L: '$CURRENT_IP' == R: '$REGISTERED_IP'"
		fi

		ERR_LAST=0
		[ $DRY_RUN -eq 0 ] && {
			send_update "$CURRENT_IP"
			ERR_LAST=$?	# save return value
		}

		# error sending current IP to provider
		# we have no communication error (handled inside send_update/do_transfer)
		# but update was not recognized
		# do NOT retry after RETRY_SECONDS, do retry after CHECK_SECONDS
		# to early retrys will block most DDNS provider
		# providers answer is checked inside send_update() function
		if [ $ERR_LAST -eq 0 ]; then
			get_uptime LAST_TIME		# we send update, so
			echo $LAST_TIME > $UPDFILE	# save LASTTIME to file
			if [ "$CURRENT_IP" != "$REGISTERED_IP" ]; then
				write_log 6 "Update successful - IP '$CURRENT_IP' send"
				eval sed -i '/^$service_name\ $lookup_host\ $use_ipv6.*/d' /tmp/ddnsmngr/registered_host
				eval echo '$service_name $lookup_host $use_ipv6 $CURRENT_IP' >> /tmp/ddnsmngr/registered_host
			else
				write_log 6 "Forced update successful - IP: '$CURRENT_IP' send"
			fi
		elif [ $ERR_LAST -eq 127 ]; then
			write_log 3 "No update send to DDNS Provider"
		else
			write_log 3 "IP update not accepted by DDNS Provider"
		fi
	elif [ "$CURRENT_IP" = "$REGISTERED_IP" ]; then
		write_log 6 "No update needed - L: '$CURRENT_IP' == R: '$REGISTERED_IP'"
	fi

	# wait before re-testing if the update was recognized: the check interval
	# normally, but the retry interval while in a retry cycle (failed update)
	[ "$RETRY_COUNT" -gt 0 ] && WAIT_SECONDS=$RETRY_UPDATE_SECONDS || WAIT_SECONDS=$CHECK_SECONDS
	[ $DRY_RUN -eq 0 ] && {
		write_log 7 "Waiting $WAIT_SECONDS seconds"
		sleep $WAIT_SECONDS &
		PID_SLEEP=$!
		wait $PID_SLEEP	# enable trap-handler
		PID_SLEEP=0
	} || write_log 7 "Dry Run: NO waiting"

	REGISTERED_IP=""		# clear variable
	get_registered_ipaddr $service_name $lookup_host $use_ipv6 REGISTERED_IP # get registered/public IP
	[ $use_ipv6 -eq 1 ] && expand_ipv6 "$REGISTERED_IP" REGISTERED_IP	# on IPv6 we use expanded version

	# IP's are still different
	if [ "$CURRENT_IP" != "$REGISTERED_IP" ]; then
		RETRY_COUNT=$(( $RETRY_COUNT + 1 ))
		# MaxRetries: stop after exactly N retries (0 = no retries)
		[ "$RETRY_COUNT" -gt "$retry_max_count" ] && \
			write_log 14 "Updating IP at DDNS provider failed after $retry_max_count retries"
		write_log 4 "Updating IP at DDNS provider failed - starting retry $RETRY_COUNT/$retry_max_count"
		continue # loop to beginning
	else
		# we checked successful the last update
		RETRY_COUNT=0			# reset error counter
	fi

	# force_update=0 or VERBOSE > 1 - leave here
	[ $VERBOSE -gt 1 ]  && write_log 7 "Verbose Mode: $VERBOSE - NO reloop"
	[ $FORCE_SECONDS -eq 0 ] && write_log 6 "Configured to run once"
	[ $VERBOSE -gt 1 -o $FORCE_SECONDS -eq 0 ] && exit 0

	write_log 6 "Rerun IP check at $(eval $DATE_PROG)"
done
# we should never come here there must be a programming error
write_log 12 "Error in 'dynamic_dns_updater.sh - program coding error"
