# shellcheck disable=1091
# vim: set ft=sh noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

set -e

[ "$OTB_TRACKER_STATUS" = "OK" ] || exit

public_ip_file="$OTB_DATA_DIR/$OTB_TRACKER_INTERFACE/public_ip"
if [ -f "$public_ip_file" ]; then
	date=$(date '+%s')
	last_update=$(stat "$public_ip_file" -c '%Y')
	elapsed_time=$((date - last_update))
	# Only update the public IP every 5 min
	[ "$elapsed_time" -lt 300 ] && exit
fi

otb_debug "Starting refreshing WAN IP/ASN informations"

url_list="
	ifconfig.ovh
	ipaddr.ovh
"

_curl() {
	curl \
		--interface "$OTB_TRACKER_DEVICE_IP" \
		--max-time "$OTB_TRACKER_TIMEOUT" \
		--silent \
		--show-error \
		"$1"
}

for url in $url_list; do
	pub_ip=$(_curl "$url" || true)
	[ "IP=$pub_ip" = "$(ipcalc.sh "$pub_ip/32" | grep IP)" ] && break
	pub_ip=
done
[ -z "$pub_ip" ] && exit 1

otb_debug "Updating public IP to $pub_ip"

pub_ip_old=$(otb_get_data "$OTB_TRACKER_INTERFACE/public_ip")
otb_set_data "$OTB_TRACKER_INTERFACE/public_ip" "$pub_ip"

asn=$(_curl https://iptoasn.isp.ovh.net/v1/as/ip/"$pub_ip")
if [ -z "$asn" ]; then
	otb_warn "Fail to refresh ASN for IP $pub_ip"
else
	otb_debug "Updating ASN to $asn for IP $pub_ip"
	otb_set_data "$OTB_TRACKER_INTERFACE/asn" "$asn"
fi

[ "$pub_ip" = "$pub_ip_old" ] && exit 0
