##!/bin/bash
# Requires: kvm, bridge-utils, uml-utilities

VM_MEM="512M"
VM_IMG="disk.img"
VM_CPU=2
VM_OPTIONS="-nographic -soundhw ac97 -usb -k fr"
VM_NET_IFACE="tap0"
VM_NET_FD=0
HOST_NET_IFACE="eth0"
HOST_IP="192.168.2.10"
HOST_NETMASK="255.255.255.0"
GW="192.168.2.254"

function vm_net_start () {
	# virtual switch
	brctl addbr br0
	brctl setfd br0 $VM_NET_FD
	brctl sethello br0 0
	brctl stp br0 off

	# virtual iface 0
	#tunctl -t $VM_NET_IFACE
	#ifconfig $VM_NET_IFACE 0.0.0.0 promisc up
	#brctl addif br0 $VM_NET_IFACE

	# real iface
	ifconfig $HOST_NET_IFACE 0.0.0.0 promisc up
	brctl addif br0 $HOST_NET_IFACE

	# network
	ifconfig br0 $HOST_IP netmask $HOST_NETMASK up
	#route del default
	route add default gw $GW
}

function vm_net_stop () {
	brctl delif br0 $HOST_NET_IFACE
	#brctl delif br0 $VM_NET_IFACE
	ifconfig $HOST_NET_IFACE down
	#ifconfig $VM_NET_IFACE down
	#tunctl -d $VM_NET_IFACE
	ifconfig br0 down
	brctl delbr br0
	ifup $HOST_NET_IFACE
}

function vm_start () {
	kvm -m $VM_MEM -smp $VM_CPU -hda $VM_IMG \
		-net nic -net tap \
		$VM_OPTIONS
}

function vm_stop () {
	pkill kvm
	reset
}

case "$1" in
	"netstart") vm_net_start ;;
	"netstop") vm_net_stop ;;
	"start") vm_net_start ; vm_start ;;
	"stop")  vm_stop ; vm_net_stop ;;
	"restart") vm_stop ; vm_net_stop ; vm_net_start ; vm_start ;;
esac

#reset
exit 0

