#!/bin/bash

BIN="$(readlink -f "$0")"
BINDIR="${BIN%/*}"
BIN="${BIN#"$BINDIR"/}"

. "$BINDIR"/.rc

coproc logger >/dev/null -t qemu-ifdown
eval exec "${COPROC[0]}<&-" ">&${COPROC[1]}" '2>&1'

down () {
    local IF BR X
    IF="$1"
    BR="$2"
    X="$3"

    /sbin/brctl delif "$BR" "$IF"
    /sbin/ip link set "$IF" down
    if /sbin/brctl show | perl -anle '/^\Q'"$BR"'\E\b/ and exit !!(@F>=4)'; then
	kill $(<"$DIR"/dhcpd/dhcpd-"$X".pid)
	LOCK="$DIR"/dhcpd/dhcpd-"$X".lock
	echo waiting for dhcpd to finish
	exec 100>"$LOCK"
	if flock -x -w 10 100; then
	    /bin/rm "$DIR"/dhcpd/dhcpd-"$X".pid
	    /sbin/ip link set "$BR" down
	    /sbin/brctl delbr "$BR"
	else
	    echo WARNING: Cannot stop dhcpd on "$BR"
	fi
    fi
}

IF="$1"
case "$IF" in
    qe*)
	down "$IF" q0 qe
	;;
    qi*)
	down "$IF" q1 qi
	;;
esac

/sbin/SuSEfirewall2 start
