#!/bin/sh

. "${PM_FUNCTIONS}"

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|tail -n +2`" ]; then
            echo "$VM"
        fi
    done
}

suspend_net()
{
    for VM in `get_running_netvms`; do
        qvm-run -u root --pass-io $VM 'service NetworkManager stop; for if in `ls /sys/class/net|grep -v "lo\|vif"`; do ip l s $if down; done; modprobe -r uhci_hcd ehci_hcd'
    done
    # Ignore exit status from netvm...
    return 0
}

resume_net()
{
    for VM in `get_running_netvms`; do
        qvm-run -u root --pass-io $VM "modprobe ehci_hcd; modprobe uhci_hcd; [ -x /bin/systemctl ] && systemctl start NetworkManager.service || service qubes_core_netvm start"
    done
    # Ignore exit status from netvm...
    return 0
}

 
case "$1" in
        resume) resume_net ;;
        suspend) suspend_net ;;
        *) exit 0 ;;
esac