#!/bin/bash
#
# KNOPPIX on User-mode Linux supprot daemon startup script
#
# GPL
#
# SUZAKI Kuniyasu <k.suzaki@aist.go.jp>
# TAN Hideyuki <tanh@alpha.co.jp>
#
UMLKNXROOT=/opt/umlknoppix
export PATH=/sbin:/usr/sbin:${UMLKNXROOT}/bin:${UMLKNXROOT}/sbin:$PATH
export LANG=C
export LANGUAGE=us

[ -h /dev/net ] && sudo rm -rf /dev/net 2>/dev/null
[ -e /dev/net ] || sudo mkdir /dev/net 2>/dev/null
[ -h /dev/net/tun ] && sudo rm -f /dev/net/tun 2>/dev/null
[ -e /dev/net/tun ] || sudo mknod /dev/net/tun c 10 200
sudo insmod tun 2> /dev/null 
sudo tunctl -d umlhub
uid=`id -u`
[ x$UID != x ] && uid=$UID
[ -z $uid ] && uid=1000

sudo tunctl -u $uid -t umlhub
sudo chmod 0777 /dev/net/tun 2>/dev/null
sudo ifconfig umlhub 10.0.0.1 netmask 255.255.255.0
sudo bash -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
sudo bash -c "echo 1 > /proc/sys/net/ipv4/conf/umlhub/proxy_arp"
if [ -f /etc/fedora-release ];then
  sudo bash -c "echo 0 > /proc/sys/kernel/exec-shield-randomize"
fi

[ -h /var/run/uml_switch.pid ] && rm -f /var/run/uml_switch.pid 2>/dev/null
if [ ! -e /var/run/uml_switch.pid ]; then
  sudo rm -rf /tmp/.uml
  mkdir /tmp/.uml
  #xterm -title "uml_switch" -e uml_switch -unix /tmp/.uml/umlhub -hub -tap umlhub &
  nohup uml_switch -unix /tmp/.uml/umlhub -hub -tap umlhub </dev/null >/tmp/.uml/switch.log 2>&1 &
  UMLSWPID="$!"
  sudo bash -c "echo $UMLSWPID > /var/run/uml_switch.pid"
fi

sleep 1
sudo iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE

[ -h /var/run/dhcpd.pid ] && rm -f /var/run/dhcpd.pid 2>/dev/null
if [ ! -e /var/run/dhcpd.pid ]; then
  sudo rm -f /tmp/.uml/dhcpd.leases
  sudo touch /tmp/.uml/dhcpd.leases
  cat >/tmp/.uml/dhcpd.conf<<__EOF__
# dhcpd.conf
#default-lease-time 600;
#max-lease-time 7200;
ddns-update-style interim;

subnet 10.0.0.0 netmask 255.255.255.0 {
  range 10.0.0.10 10.0.0.100;
  option domain-name "uml.org";
  option domain-name-servers 10.0.0.1;
  option routers 10.0.0.1;
  option subnet-mask 255.255.255.0;
  option broadcast-address 10.0.0.255;
}
__EOF__

  #xterm -title "dhcpd3" -e sudo dhcpd3 -f -d -cf /tmp/.uml/dhcpd.conf -lf /tmp/.uml/dhcpd.leases umlhub &
  nohup sudo dhcpd -d -cf /tmp/.uml/dhcpd.conf -lf /tmp/.uml/dhcpd.leases umlhub > /tmp/.uml/dhcpd.log 2>&1 &

fi

[ -h /var/run/dnsmasq.pid ] && rm -f /var/run/dnsmasq.pid 2>/dev/null
if [ ! -e /var/run/dnsmasq.pid ]; then
  #xterm -title "dnsmasq" -e sudo dnsmasq --no-daemon --interface umlhub && sudo killall dnsmasq &
  sleep 1
  sudo $UMLKNXROOT/sbin/dnsmasq --interface umlhub &
fi

for i in 90 91 92 93 94 95 96 97 98 99 100
do
xhost +10.0.0.$i
done

exit 0
