#!/bin/sh -e

### BEGIN INIT INFO
# Provides:          loopback-addr
# Required-Start:    $network $syslog
# Required-Stop:     $network $syslog
# X-Interactive:     true
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Anycast address service
### END INIT INFO

DESC="loopback address(es)"
CONFDIR=/etc/loopback-addr

address_active () {
    ip addr show dev lo|grep -E "inet6? $1/[0-9]+ scope global" > /dev/null
}

start () {
    if test -e ${CONFDIR}/$1.conf; then
        if address_active $1; then
            echo -n " [$1 already active]"
        else
            ip addr add $1/32 dev lo
            echo -n " [$1]"
        fi
    else
        echo -n " ($1 not configured as loopback address)" >&2
        STATUS=1
    fi
} # start ()

stop () {
    if test -e ${CONFDIR}/$1.conf; then
        if address_active $1; then
            ip addr del $1/32 dev lo
            echo -n " [$1]"
        else
            echo -n " [$1 not active]"
        fi
    else
        echo -n " ($1 not configured as loopback address)" >&2
        STATUS=1
    fi
} # stop ()

status () {
    if test -e ${CONFDIR}/$1.conf; then
        if address_active $1; then
            echo
            echo -n "[$1 active]"
        else
            echo
            echo -n "[$1 not active]"
        fi
    else
        echo " ($1 not configured as loopback address)" >&2
        STATUS=1
    fi
} # status ()

do_command () {
    command=$1
    shift
    if test 0 -eq $#; then
        for addr in $(cd ${CONFDIR} && ls *.conf); do
            $command $(basename $addr .conf)
        done
    else
        while test 0 -lt $#; do
            $command $1
            shift
        done
    fi
} # do_command ()

CMND="$1"
shift

case "$CMND" in
    start|status|stop)
        echo -n "$CMND $DESC:"
        do_command $CMND "$@"
        echo
        exit ${STATUS:-0}
        ;;
    restart)
        $0 stop "$@"
        $0 start "$@"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}" >&2
        exit 1
esac

exit 0

# vim: set ft=sh sw=4 ts=4 tw=78 et si:
