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

net="
-net nic,model=e1000
-net tap,ifname=tap1"

#-net user,hostfwd=192.168.2.250:4242:127.0.0.1:22
#,guestfwd=tcp:127.0.0.1:6000-lo
#	-net tap,ifname=tap1 \

if [ -z "$1" ]; then
	:
#	set -- "$@" -nographic
#	set -- "$@" -curses
#	set -- "$@" -serial stdio -monitor stdio
#	set -- "$@" -serial stdio
#	set -- "$@" -serial /dev/ttyS0
#	set -- "$@" -serial tcp::4444,server,nowait
#	set -- "$@" -serial tcp::4444,server
#	set -- "$@" -redir tcp:4222:192.168.10.2:22
#	set -- "$@" -serial pty
	if [ -z "$DISPLAY" ]; then
#		set -- "$@" -nographic
		set -- "$@" -nographic -pidfile ac-ppc.pid -daemonize
	fi
fi

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

#cmdline="console=tty1 console=ttyS0,19200n8"
#cmdline="console=tty1 console=ttyS0,115200n8"
#cmdline="console=tty1"
#cmdline="init=/bin/sh"

#sysctl -w net.ipv4.ip_forward=1
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-ppc)" ]; then
	echo >&2 "qemu-system-ppc already running"
	exit 1
fi

e2fsck -y ac-ppc.img
e2fsck -y ac-ppc-builder.img

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

qemu-system-ppc \
	-hda ac-ppc.img \
	-name ppc-builder \
	-hdb ac-ppc-builder.img \
	-hdc swap.img \
	-m 512 \
	$net \
	-kernel boot/vmlinuz -initrd boot/initrd -append "root=/dev/hda ro $cmdline" \
	"$@"
