#!/bin/sh
#
# chkconfig: 2345 81 00
# description: Starts/stops Qubes default netvm
#
### BEGIN INIT INFO
# Provides:          qubes-networking
# Required-Start:    qubes-core
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Default-Enabled:   yes
# Short-Description: Start/stop qubes networking
# Description:       Starts and stops the qubes networking
### END INIT INFO


#
# Source function library.
. /etc/rc.d/init.d/functions

NETVM=$(qvm-get-default-netvm)

get_running_netvms() {
    # Actually get running VMs with PCI devices attached
    RUNNING_VMS=`xl list | tail -n +3 | cut -f 1 -d " "`
    RUNNING_NETVMS=""
    for VM in $RUNNING_VMS; do
        if [ -n "`xl pci-list $VM`" ]; then
            echo "$VM"
        fi
    done
}

start()
{
    if [ x$NETVM = x ] ; then

        echo WARNING: Qubes NetVM not configured!
        echo -n $"Doing nothing:"

    else

        echo -n $"Starting default NetVM:"
        DISPLAY=:0 sg qubes "qvm-start -q --no-guid $NETVM" || exit 1

    fi
    touch /var/lock/subsys/qubes_netvm
    success
    echo
	return 0
}

stop()
{
    if [ x$NETVM = x ] ; then

        echo WARNING: Qubes NetVM not configured!
        echo -n $"Doing nothing:"

    else

        echo -n $"Stopping NetVMs:"
        for VM in `get_running_netvms`; do
            qvm-run -q --force --shutdown --wait $VM
        done

    fi
    rm -f /var/lock/subsys/qubes_netvm
    success
    echo

	return 0
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  *)
	echo $"Usage: $0 {start|stop}"
	exit 3
	;;
esac

exit $RETVAL