#!/bin/sh
UML_ID="shadowsocks"
TAP_DEV="tap0"
ROUTER_DEV="venet0"
TAP_ADDR="192.168.0.3"
UML_ADDR="192.168.0.4"
REV_TCP_PORTS=""
REV_UDP_PORTS=""
FWD_TCP_PORTS="9443"
FWD_UDP_PORTS="9443"

DIR="$( cd "$( dirname "$0" )" && pwd )"

[ ! -d /sys/class/net/$TAP_DEV ] && tunctl -t $TAP_DEV
ifconfig $TAP_DEV $TAP_ADDR up

echo 1 > /proc/sys/net/ipv4/ip_forward

iptables -t nat -I POSTROUTING -o $ROUTER_DEV -j MASQUERADE

for i in $REV_TCP_PORTS; do
	if [ "x$i" = "x*" ]; then
		P_TMP=""
	else
		P_TMP="--dport $i "
	fi
	iptables -t nat -A PREROUTING -p tcp $P_TMP-j RETURN
done
for i in $REV_UDP_PORTS; do
	if [ "x$i" = "x*" ]; then
		P_TMP=""
	else
		P_TMP="--dport $i "
	fi
	iptables -t nat -A PREROUTING -p udp $P_TMP-j RETURN
done

for i in $FWD_TCP_PORTS; do
	if [ "x$i" = "x*" ]; then
		P_TMP=""
	else
		P_TMP="--dport $i "
	fi
	iptables -t nat -A PREROUTING -i $ROUTER_DEV -p tcp $P_TMP-j DNAT --to-destination $UML_ADDR
done
for i in $FWD_UDP_PORTS; do
	if [ "x$i" = "x*" ]; then
		P_TMP=""
	else
		P_TMP="--dport $i "
	fi
	iptables -t nat -A PREROUTING -i $ROUTER_DEV -p udp $P_TMP-j DNAT --to-destination $UML_ADDR
done

nohup $DIR/vmlinux-i686 umid=$UML_ID root=/dev/root rootfstype=hostfs rootflags=$DIR/umlfs-i686 rw mem=48M init=/sbin/init con=pts eth0=tuntap,$TAP_DEV,,$UML_ADDR &
