#!/bin/bash

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

. "$BINDIR"/.rc

# qemu leaks file descriptors here.
# so, we need to close them before starting dhcpd
for (( i=3; i<256; i++ )); do
    eval "exec $i<&-"
done

IF="$1"
case "$IF" in
    qe*)
	grep -q q0: /proc/net/dev || {
	    /sbin/brctl addbr q0
	    /sbin/ip addr add $Q0ADDR/24 dev q0
	    /sbin/ip link set q0 up
	    for i in "${RESTART_SERVICES[@]}"; do
		/etc/init.d/$i restart
	    done
	}
	/sbin/ip link set "$IF" up
	/sbin/brctl addif q0 "$IF"
	LOCK="$DIR"/dhcpd/dhcpd-qe.lock
	exec 100>"$LOCK"
	if flock -x -n 100; then
	    : >>"$DIR"/dhcpd/dhcpd-qe.leases
	    /usr/sbin/dhcpd -cf "$DIR"/dhcpd/dhcpd-qe.conf \
                            -lf "$DIR"/dhcpd/dhcpd-qe.leases \
                            -pf "$DIR"/dhcpd/dhcpd-qe.pid q0
	fi
	;;
    qi*)
	grep -q q1: /proc/net/dev || {
	    /sbin/brctl addbr q1
	    /sbin/ip addr add $Q1ADDR/24 dev q1
	    /sbin/ip link set q1 up
	    for i in "${RESTART_SERVICES[@]}"; do
		/etc/init.d/$i restart
	    done
	}
	/sbin/ip link set "$IF" up
	/sbin/brctl addif q1 "$IF"
	LOCK="$DIR"/dhcpd/dhcpd-qi.lock
	exec 100>"$LOCK"
	if flock -x -n 100; then
	    : >>"$DIR"/dhcpd/dhcpd-qi.leases
	    /usr/sbin/dhcpd -cf "$DIR"/dhcpd/dhcpd-qi.conf \
                            -lf "$DIR"/dhcpd/dhcpd-qi.leases \
                            -pf "$DIR"/dhcpd/dhcpd-qi.pid q1
	fi
	;;
esac

/sbin/SuSEfirewall2 start
