#!/bin/bash

# function to exit with message and code
die() {
	[[ -n "$2" ]] && printf "%s\n" "$2"
	[[ -n "$1" ]] && exit "$1" || exit 127
}

url="https://dyn.dns.he.net/nic/update"
config="/etc/he-ddnsrc"
ip_host="icanhazip.com"

help_text="Usage: $0 [OPTIONS]
Update Hurricane Electric Dynamic DNS for domains in the configuration file
with associated keys. Requires curl to be installed in \$PATH.

Options:
  -c, --config FILE     get configuration from FILE instead of $config
  -u, --url URL         update dns at URL instead of $url
  -h, --help            display this help

https://gitlab.com/rascul/he-ddns
"

show_help() {
	printf "%s" "$help_text"
}

while (($#)); do
	case $1 in
		-c|--config)
			if [[ -n "$2" ]]; then
				config="$2"
				shift
			else
				die $LINENO "$help_text"
			fi
			;;
		-h|--help)
			show_help
			exit
			;;
		*)
			args+=("$1")
			;;
	esac
	shift
done

# shellcheck source=he-ddnsrc
. "$config" || die $LINENO

if [[ -n "${DOMAINS4[*]}" ]]; then
	ipv4="$(curl -sSL4 "$ip_host")" || die $LINENO
	for domain in "${!DOMAINS4[@]}"; do
		printf "%s :: " "$domain"
		key=${DOMAINS4[$domain]}
		curl -sSL4 "$url" -d "hostname=$domain" -d "password=$key" -d "myip=$ipv4" || die $LINENO
		echo
	done
fi

if [[ -n "${DOMAINS6[*]}" ]]; then
	ipv6="$(curl -sSL6 "$ip_host")" || die $LINENO
	for domain in "${!DOMAINS6[@]}"; do
		printf "%s :: " "$domain"
		key=${DOMAINS6[$domain]}
		curl -sSL6 "$url" -d "hostname=$domain" -d "password=$key" -d "myip=$ipv6" || die $LINENO
		echo
	done
fi
