#!/bin/sh

PATH=`dirname $0`:$PATH:/sbin

network=`get-uml-config network 192.168.162`

if [ $? -ne 0 ]; then
  echo "Unable to run get-uml-config"
  exit 1
fi

hostip=`get-uml-config hostip ${network}.1`
netmask=`get-uml-config netmask 255.255.255.0`
broadcast=`get-uml-config broadcast ${network}.255`

if [ `whoami` != "root" ]; then
  echo "$0 must be run as root"
  exit 1
fi

MSG=

# See if a tap device is already configured
if [ -f .tap ]; then
  ifconfig `cat .tap` >/dev/null 2>&1
  if [ $? -ne 0 ]; then
    # Device doesn't exist
    rm -f .tap
  fi
fi

if [ ! -f .tap ]; then
  # Need to create a tap device
  if [ $# -ne 1 ]; then
    echo "Usage: $0 <username>"
    exit 1
  fi

  modprobe tun
  if [ $? -ne 0 ]; then
    echo "Failed to install create permanent tuntap. Are you running as root?"
    exit 1
  fi

  chmod 666 /dev/net/tun 2>/dev/null

  tunctl -b -u "$1" 2>/dev/null >.tap

  if [ $? -ne 0 ]; then
    echo "Failed to create permanent tuntap. Are you running as root? Do you have uml_utilities installed?"
    rm -f .tap
    exit 1
  fi
  MSG="(created for user $1)"
fi

TAP=`cat .tap`

echo "Using tap: $TAP $MSG"

ifconfig $TAP $hostip netmask $netmask broadcast $broadcast up
if [ $? -ne 0 ]; then
  echo "ifconfig $TAP failed"
  tunctl -d $TAP
  rm -f .tap
  exit 1
fi

echo "Configured $TAP with IP address: $hostip"
