#!/bin/sh

# vnc listen address
vnc=:1

# tap interface to create
tap_if=tap2
# ip of tap interface to give on host side
export qemu_tap_ip=192.168.11.1

# see if we called as script for net
if [ "$1" = "$tap_if" ]; then
	exec sudo /sbin/ifconfig $1 $qemu_tap_ip
	exit 1
fi

if [ "$(id -u)" != "0" ]; then
	echo >&2 "Need to run as root"
	exit 1
fi

make_images() {
	set -x
	test -e ac-sparc.img || {
		dd if=/dev/zero of=ac-sparc.img bs=1M count=512
		mkfs.ext3 -L ac-sparc ac-sparc.img
	}

	test -e ac-sparc-builder.img || {
		dd if=/dev/zero of=ac-sparc-builder.img bs=1M count=128
		mkfs.ext3 -L ac-sparc-builder ac-sparc-builder.img
	}

	test -e ac-sparc-swap.img || {
		dd if=/dev/zero of=ac-sparc-swap.img bs=1M count=128
		mkswap -L ac-sparc-swap ac-sparc-swap.img
	}
}

net="
-net nic,model=lance
-net tap,ifname=$tap_if,script=$0
"

if [ -z "$1" ]; then
	if [ -z "$DISPLAY" ]; then
		set -- "$@" -nographic -pidfile ac-sparc.pid -daemonize
		# qemu tends to fckup terminal input, so that reset(1) needs to be called. workaround
#		exec </dev/null
	fi
fi

if [ "$(id -u)" = "0" ]; then
	set -- "$@" -runas ${SUDO_USER:-$USER}
fi

if [ "$(sysctl -n net.ipv4.ip_forward)" != "1" ]; then
	echo >&2 "net.ipv4.ip_forward is not enabled, network routing will not work"
	exit 1
fi

if [ "$(iptables -L -n -t nat 2>/dev/null | grep -c MASQUERADE)" = "0" ]; then
	echo >&2 "no MASQUERADE nat rules, network may not work"
	exit 1
fi

if [ -n "$(/sbin/pidof qemu-system-sparc)" ]; then
	echo >&2 "qemu-system-sparc already running"
	exit 1
fi

make_images

# first try autofsck, skip on errors
e2fsck -y ac-sparc.img
e2fsck -y ac-sparc-builder.img

# if it exits nonzero on second try, it is seriously broken
e2fsck -y ac-sparc.img || exit 1
e2fsck -y ac-sparc-builder.img || exit 1

# setup serial and normal console
cmdline="$cmdline console=tty0 console=ttyS0"

qemu-system-sparc \
	-hda ac-sparc.img \
	-name sparc-builder \
	-hdb ac-sparc-builder.img \
	-hdc ac-sparc-swap.img \
	-m 256 \
	-serial telnet:localhost:2323,server,nowait,nodelay \
	$net \
	${vnc:+-vnc $vnc} \
	-kernel boot/vmlinux.aout -initrd boot/initrd -append "root=/dev/sda ro $cmdline" \
	"$@"
