#!/bin/sh

. /etc/tinc/${NETNAME}/config/ula_prefix

ULA_SUBNET="/32"
ETCHOSTS="/etc/hosts"
# Added at the end of each line in the hosts file.
COMMENT="# Managed by tinc ${NETNAME}"

mac_to_address() {
  # Turns every octet into a positional variable.
  # $1 = 12:3:56:78:9a → $1 = 12, $2 = 3, $3 = 56 …
  local IFS=:; set $1
  printf '%2s%2s:%2s%2s:%2s%2s' $@ | tr ' ' '0'
}

case $2 in
  subnet)
    _mac="$(mac_to_address "${SUBNET}")"
    IP="${ULA_PREFIX}::${_mac}"
    if test "${ULA_SUBNET}" = "/32"; then
      case $1 in
        up) ip -6 route add "${ULA_PREFIX}:${_mac}::/80" via "${IP}" dev "${INTERFACE}" ;;
        down) ip -6 route del "${ULA_PREFIX}:${_mac}::/80" via "${IP}" dev "${INTERFACE}" ;;
      esac
    fi
    ;;
  tinc)
    MAC="$(cat "/sys/class/net/${INTERFACE}/address")"
    IP="${ULA_PREFIX}::$(mac_to_address "${MAC}")"
    case $1 in
      up) ip address add "${IP}${ULA_SUBNET}" dev "${INTERFACE}" ;;
      down) sed -re "/${COMMENT}$/d" -i "${ETCHOSTS}" ;;
    esac ;;
esac

test -z "${NODE}" && exit

sed -re "/${NODE}\.${NETNAME} ${COMMENT}$/d" -i "${ETCHOSTS}"
sed -re "/^${IP} .* ${COMMENT}$/d" -i "${ETCHOSTS}"

if test "$1" = "up"; then
  echo "${IP} ${NODE}.${NETNAME} www.${NODE}.${NETNAME} ${COMMENT}" >> "${ETCHOSTS}"
fi
