#!/bin/sh -e
#
# see https://dynv6.com/ there host->instructions
#
hostname=$1
device=$2
file=$HOME/.dynv6.addr6
[ -e $file ] && old=`cat $file`

# Tokens are given once to the dynv6.com account (email).
#token="abcdefghijkl"
#hostname=`hostname`"-telekom.dynv6.net"

if [ -z "$hostname" -o -z "$token" ]; then
  echo "Usage: token=<your-authentication-token> [netmask=64] $0 your-name.dynv6.net [device]"
  exit 1
fi


if [ -z "$netmask" ]; then
  netmask=128
fi

if [ -n "$device" ]; then
  device="dev $device"
fi
address=$(ip -6 addr list scope global $device | grep -v " fd" | sed -n 's/.*inet6 \([0-9a-f:]\+\).*/\1/p' | head -n 1)
# v4_address=$(ip -4 addr list $device | grep "global" | sed -n 's/.*inet \([0-9.]\+\).*/\1/p' | head -n 1);

if [ -e /usr/bin/curl ]; then
  bin="curl -fsS"
elif [ -e /usr/bin/wget ]; then
  bin="wget -O-"
else
  echo "neither curl nor wget found"
  exit 1
fi

if [ -z "$address" ]; then
  echo "no IPv6 address found"
  exit 1
fi

# address with netmask
current=$address/$netmask

if [ "$old" = "$current" ]; then
  echo "IPv6 address unchanged"
  exit
fi

# send addresses to dynv6
# IPv6
#$bin "http://dynv6.com/api/update?hostname=$hostname&ipv6=$current&token=$token"
echo "http://dynv6.com/api/update?hostname=$hostname&ipv6=$current&token=$token"

# IPv4
# [auto|v4_address]: auto means that ipv4.dynv6.com tracks the call back to the last non-private IP.
#$bin "http://ipv4.dynv6.com/api/update?hostname=$hostname&ipv4=auto&token=$token"
echo "http://ipv4.dynv6.com/api/update?hostname=$hostname&ipv4=auto&token=$token"

# save current address
echo $current > $file
