#! /bin/sh
#
# uml-utilities Provide some simple UML networking configuration
#               services
#
#               Matt Zimmerman <mdz@debian.org>
#               Bart Trojanowski <bart@jukie.net> - multiple device support

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/uml_switch
NAME=uml_switch
DESC="User-mode networking switch"

test -x $DAEMON || exit 0

set -e

UML_SWITCH_DEVICES=""
UML_SWITCH_OPTIONS=""
UML_SWITCH_USER="uml-net"
UML_SWITCH_CTL="/var/run/uml-utilities/uml_switch.ctl"

if [ -e /etc/default/uml-utilities ]; then
  . /etc/default/uml-utilities
fi

function dev_variables() {

        DEV=$1
        
        DEV_OPTS=$(eval "echo \$UML_SWITCH_OPTIONS_$DEV")
        DEV_OPTS=${DEV_OPTS:-$UML_SWITCH_OPTIONS}

        DEV_USER=$(eval "echo \$UML_SWITCH_USER_$DEV")
        DEV_USER=${DEV_USER:-$UML_SWITCH_USER}

        DEV_CTL=$(eval "echo \$UML_SWITCH_CTL_$DEV")
        DEV_CTL=${DEV_CTL:-$UML_SWITCH_CTL}

        DEV_PIDFILE=/var/run/uml-utilities/$NAME.$DEV.pid

        DEV_OPTIONS="-tap $DEV -unix $DEV_CTL"

}

function start() {

        DEV=$1
        
        dev_variables $DEV

	echo -n " $DEV"
        mkdir -p /var/run/uml-utilities
        chown uml-net.uml-net /var/run/uml-utilities
        start-stop-daemon --start --quiet --pidfile $DEV_PIDFILE \
            --make-pidfile --background --chuid $DEV_USER \
            --exec $DAEMON -- $DEV_OPTIONS

        WAIT=5
        while ! test -e $DEV_CTL; do
            sleep 1
            WAIT=$(($WAIT - 1))
            if [ $WAIT -le 0 ]; then
                echo " [FAILED]"
                echo "$NAME on $DEV: $DAEMON never created control socket $DEV_CTL" >&2
                return -1
            fi
        done

        chmod 777 $DEV_CTL
	echo -n " [OK]  "
}

function stop() {

        DEV=$1

        dev_variables $DEV
        
	echo -n " $DEV"
        start-stop-daemon --stop --quiet --pidfile $DEV_PIDFILE \
            --oknodo --exec $DAEMON
        rm -f $DEV_PIDFILE $DEV_CTL
	echo -n " [OK]  "
}

# read the command command
cmd=$1
shift

# parameters that follow the command are devices that override the defaults
DEVICES=${@:-$UML_SWITCH_DEVICES}

case "$cmd" in
  start)
	echo -n "Starting $DESC: $NAME on... "
        for dev in $DEVICES ; do
                start $dev
        done
        echo .
	;;
  stop)
	echo -n "Stopping $DESC: $NAME on... "
        for dev in $DEVICES ; do
                stop $dev
        done
        echo .
	;;
  restart|force-reload)
        $0 stop  ${1+"$@"}
        $0 start ${1+"$@"}
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload} [<device> ...]" >&2
	exit 1
	;;
esac

exit 0
