#!/bin/sh
echo "99avahi arg=$1" > /dev/ttyS0
[ -z "$1" ] && echo "Error: should be called from udhcpc" && exit 1

if [ "$(cat /var/run/99avahi_nesting)" == "second" ]
then
        case "$1" in
                bound)
                echo "99avahi second nesting: bound" > /dev/ttyS0
                echo "bound" > /var/run/99avahi_status
                ;;

                *)
                echo "99avahi second nesting: unbound" > /dev/ttyS0
                rm /var/run/99avahi_status
                ;;
        esac
        exit 0
fi
case "$1" in
        leasefail)
        if [ "$(cat /etc/network/configuration)" == "DHCP" ]
        then
                rm /var/run/99avahi_status
                while [ "$(ifplugstatus $interface)" == "$interface: link beat detected" ]
                do
                        if [ "$(cat /var/run/99avahi_status)" == "bound" ]
                        then
                                echo "99avahi first nesting: bound" > /dev/ttyS0
                                exit 0
                        fi
                        echo "99avahi first nesting: unbound" > /dev/ttyS0
                        echo "99avahi leasefail: DHCP only, retrying" > /dev/ttyS0
                        #kill -SIGUSR1 $(cat /var/run/udhcpc.eth0.pid)
                        echo "second" > /var/run/99avahi_nesting
                        udhcpc -R -n -p /var/run/udhcpc.eth0.pid -i eth0 -t1
                        rm /var/run/99avahi_nesting
                done
        else
                echo "99avahi leasefail: AUTO, falling back to zeroconf" > /dev/ttyS0
                /usr/sbin/avahi-autoipd --no-drop-root -wD $interface 2> /dev/null
        fi
        ;;
esac
