#! /bin/sh
### BEGIN INIT INFO
# Provides:           xsupplicant
# Required-Start:     $network
# Default-Start:      S
# Default-Stop:       0 6
# Short-Description:  802.1x supplicant
# Description:        Debian init script for xsupplicant
### END INIT INFO
#
# xsupplicant    IEEE 802.1x supplicant (client)
# 
# Author:        Eric Evans <eevans@sym-link.com>

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/xsupplicant
NAME=xsupplicant
DESC="802.1x supplicant"

set -e

test -x $DAEMON || exit 0

ENABLED=0

# Include xsupplicant defaults if available
if [ -r /etc/default/xsupplicant ] ; then
    . /etc/default/xsupplicant
fi

if [ "$ENABLED" = "0" ] ; then
    echo "$DESC: disabled, see /etc/default/$NAME"
    exit 0
fi

# Get the interface name out of the argument list for the name of the 
# pid file.
INTERFACE=`echo "$ARGS" | sed -e "s/.*-i[[:space:]]*\([[:alnum:]]\+\).*/\1/"`

PIDFILE=/var/run/$NAME.$INTERFACE.pid

DAEMON_OPTS="$ARGS"

stillrunning()
{
    if [ ! -f "$PIDFILE" ] ; then
        return 1
    fi
    
    pid=`cat $PIDFILE`

    if [ -z "$pid" ] ; then
        rm -f "$PIDFILE"
        return 1
    fi

    cmd=`cat /proc/$pid/cmdline 2>/dev/null | tr "\000" "\n"| head -n 1`

    if expr "$cmd" : "$DAEMON" >/dev/null 2>&1 ; then
        return 0
    else
        rm -f "$PIDFILE"
        return 1
    fi
}

case "$1" in
    start)
        echo -n "Starting $DESC: "
        if ! stillrunning ; then
            start-stop-daemon --start --quiet --pidfile $PIDFILE \
                --exec $DAEMON -- $DAEMON_OPTS >/dev/null
        fi
        echo "$NAME."
        ;;
    stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon -o --stop --quiet --retry 5 --pidfile $PIDFILE \
            --exec $DAEMON
        if stillrunning ; then
            echo "failed to shutdown" 2>&1
        else
            echo "$NAME."
        fi
        ;;
    restart|force-reload)
        echo -n "Restarting $DESC: "
        start-stop-daemon -o --stop --quiet --retry 5 --pidfile $PIDFILE \
            --exec $DAEMON
        if ! stillrunning  ; then
            start-stop-daemon --start --quiet --pidfile $PIDFILE \
                --exec $DAEMON -- $DAEMON_OPTS >/dev/null
            echo "$NAME."
        else
            echo "failed to restart" 2>&1
        fi
        ;;
    status)
        echo -n "$DESC: "
        xsup_get_state $INTERFACE
        ;;
    *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|status|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0

# vim:set ai ts=4 tw=0 expandtab:
