#! /bin/sh
### BEGIN INIT INFO
# Provides:           xsupplicant
# Required-Start:     $local_fs
# Required-Stop:      $local_fs
# Default-Start:      S
# Default-Stop:       0 6
# Short-Description:  802.1x/802.11i supplicant
# Description:        Debian init script for xsupplicant
### END INIT INFO
#
# 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 3
    fi
    
    pid=`cat $PIDFILE`

    if [ -z "$pid" ] ; then
        rm -f "$PIDFILE"
        return 3
    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 3
    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
        ;;
    try-restart|force-reload)
        if stillrunning; then
            exec $0 restart
	    fi
	    ;;
    reload)
        echo "Reload not supported for $DESC. Try 'force-reload' instead."
	    exit 3
	    ;;
    restart)
        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
        exit `stillrunning`
        ;;
    *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|status|restart|try-restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0

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