#!/bin/bash

#nop=echo

# Which image to test
dist=lenny-test-i386
archlist=i386
size="-CD700"

gwmem=64
mem=128
gtkinstmem=160
ltspmem=64
disksizegb=17

disksize=$(($disksizegb * 1024 * 1024))

if [ -z "$image" ]; then
    image=etch-test-amd64-i386-powerpc-DVD-1.iso
    image=$dist-$archlist-1.iso
fi
if true ; then
    rsyncopts="--progress -vt"
    $nop rsync $rsyncopts \
	ftp.skolelinux.no::cd-$dist/debian-edu-$archlist$size-1.iso $image
fi

pxeimage=gpxe-0.9.3-rtl8139.iso
if [ ! -f $pxeimage ] ; then
    echo "Missing PXE boot ISO $pxeimage."
    echo "Fetch 'rtl8139:pci_10ec_8139 - 10ec,8139' from http://rom-o-matic.net/."
    exit 1;
fi

gwimage="floppyfw-3.0.5.iso"
if [ ! -f $gwimage ] ; then
    wget http://www.zelow.no/floppyfw/download/floppyfw-3.0/floppyfw-3.0.5/floppyfw-3.0.5.iso
fi

if [ ! -f hda-main ] ; then
    $nop qemu-img create hda-main $disksize
fi

if [ ! -f hda-ws ] ; then
    $nop qemu-img create hda-ws $disksize
fi

#opts="-soundhw es1370"

netdef() {
    type=$1
    mac=$2
    case $type in
	internet)
	    echo \
		-net nic,model=rtl8139,vlan=1,macaddr=$mac \
		-net user,vlan=1
	    ;;
	backbone)
	    echo \
		-net nic,model=rtl8139,vlan=2,macaddr=$mac \
		-net socket,mcast=230.0.0.1:1232,vlan=2
	    ;;
	thinnet)
	    echo \
		-net nic,model=rtl8139,vlan=3,macaddr=$mac \
		-net socket,mcast=230.0.0.1:1233,vlan=3
	    ;;
    esac
}

$nop qemu $opts -m $mem $internet \
    -boot d \
    -cdrom $image \
    -hda hda-main

echo
echo "Restarting qemu with boot from HD.  Press [enter] to continue."
$nop read

# Start gateway
$nop qemu $opts -m $gwmem \
    $(netdef internet 52:54:00:12:35:01) \
    $(netdef backbone 52:54:00:12:35:02) \
    -boot d \
    -cdrom $gwimage &

if false; then
    # Running too many qemu machines on the net messes up the PXE
    # boot, it seem.
    ( # Wait for the main-server to get dhcp and tftp working
    sleep 120
    # Start thin client
    $nop qemu $opts -m $ltspmem \
	$(netdef thinnet 52:54:00:12:35:03) \
	-boot d \
	-cdrom $pxeimage &

    # Start diskless workstation
    $nop qemu $opts -m $mem \
	$(netdef backbone 52:54:00:12:35:04) \
	-boot d \
	-cdrom $pxeimage &
    )
fi

# Starting workstation, after the main-server is booted
(
    sleep 120
    $nop qemu $opts -m $gtkinstmem \
	$(netdef backbone 52:54:00:12:35:05) \
	-boot d \
	-cdrom $pxeimage \
	-hda hda-ws
) &

# Starting server
$nop qemu $opts -m $mem \
    $(netdef backbone 52:54:00:12:35:06) \
    $(netdef thinnet 52:54:00:12:35:07) \
    -boot c \
    -cdrom $image \
    -hda hda-main
