#!/bin/bash
export PATH="$PATH:/sbin:/usr/sbin"

# Figure out the cwtap's IP address by examining the last two bytes
# of the host interface's MAC address.
let byte4=0x$(cat /sys/$DEVPATH/address|cut -d: -f5)
let byte5=0x$(cat /sys/$DEVPATH/address|cut -d: -f6)
devip=169.254.$byte4.$byte5

# Fallback auto-ip functions if avahi isn't found
RANDOM=$(date +%s)
default_addip ()
{
  # only try 10 times - some older distributions incorrectly respond to ping
  # on all link-local addresses
  for i in $(seq 1 10); do
    ip=169.254.$(expr $RANDOM % 256).$(expr $RANDOM % 256)
    ping -c 1 $ip || break
  done
  ip address add dev $INTERFACE scope link local "$ip/16" broadcast +
  ip link set $INTERFACE up
}
default_removeip ()
{
  ip link set $INTERFACE down
  ip=$(ip addr show $INTERFACE |grep "inet "|cut -d' ' -f6|cut -d/ -f1)
  ip address del dev $INTERFACE local $ip
}

if ! service network-manager status 2>&1 | grep -q running; then
  ADDIP=default_addip
  REMOVEIP=default_removeip
fi

case "$ACTION" in
  remove)
    route del -host $devip metric 0 $INTERFACE
    $REMOVEIP
    ;;
  add)
    $ADDIP
    route add -host $devip metric 0 $INTERFACE
    ;;
esac
