#!/bin/bash
myname=$( basename $0 )

function usage() {

echo "
`basename $0`: (-h hostname|-p password|-c cgi-url|-a address|-6|--help)
hostname:	the hostname that shall be updated.
password:	the password for the host on the server.
cgi:		the complete URL to the CGI script on the server
address:	ipv4 address
-6 prevents the detection of ipv6 addresses and their update.

https://build.opensuse.org/package/show/home:draht/dyndns-lite
Send patches to draht at schaltsekun.de (Roman Drahtmueller)
"
}

while [ ! -z "$1" ]; do
  case "$1" in
    -h)
	shift
	host="$1"
	shift
	;;
    -p)
	shift
	pass="$1"
	shift
	;;
    -c)
	shift
	cgi="$1"
	shift
	;;
    -a)
	shift
	addr="$1"
	shift
	;;
    -6)
	shift
	skip6=1
	;;
    --help)
	usage
	exit 0
	;;
    *)
	;;
  esac
done

err=0
for i in cgi pass host; do
  if [ -z "${!i}" ]; then
    echo "$i has no value."
    err=1
  fi
done
if [ "$err" = 1 ]; then
  usage
  exit 1
fi

if [ -z "$addr" ]; then
default_interface=$( ip -4 -o r l to default| \
	awk '{ a=0; 
		while ($a != "") { 
		    if($a == "dev") {
			 a++; print $a; exit; 
		    }; 
		    a++; 
		}
		}'
)

export default_interface
addr=$(
ip -4 -o a l dev $default_interface | \
	awk '
		{ a=0; 
		while ($a != "") { 
		    if($a == "inet" ) { 
			a++; host=$a;
			split(host, s, "/");
			printf("%s\n" , s[1]);
			exit 0;
		    };
		    a++; 
		   }
		}'
)
fi

if [ -z "$skip6" ]; then
# ipv6 may be routed through a different interface such as a tunnel etc
default_6_interface=$( ip -6 -o r l to default | \
	awk '
		{ a=0;
		while ($a != "") {
		    if($a == "dev") {
			a++; print $a; exit;
		    };
		    a++;
		}
		}'
)
export default_6_interface
if [ ! -z "$default_6_interface" ]; then
addr6=$(
ip -6 -o a l dev $default_6_interface scope global | \
	awk '/inet6 2.*/ { 
		if($0 ~ " deprecated ") { 
		    next;
		};
		a=0;
		while ($a != "") {
		    if($a == "inet6" ) {
			a++; host=$a;
			split(host, s, "/");
			printf("%s\n" , s[1]);
			exit 0;
		    };
		    a++;
		}
	}'
)
fi # ipv6 default gw interface is known
fi # skip6 non-empty

# only send the ipv6 string if there is an address:
if [ ! -z "$addr6" ]; then
  six_string="ipv6=$addr6"
fi

curl -k -d "
ip=$addr
host=$host
pass=$pass
$six_string
" "$cgi"

