#!/bin/bash
#
# shell script to set up adhoc wireless network sharing on Linux
# (C) 2007 havard@dahle.no
# you are free to use and modify this script in whatever way possible

ESSID=punktpunkt # name of adhoc network

# you may set these variables if the script does not figure it out by itself
#WIRE=eth0                 # default: eth0
#WLAN=eth1                 # default: first wlan adapter, or eth1

DATE=$(date);

function find_wlan_adapter {
  adapter=$(cat /proc/net/wireless | sed -n '3~0p' | cut -d: -f1 | sed 's/\s//g');
  echo $adapter;
}

function check_wlan_adapter {
  iwconfig $1 2>&1 | grep "No such device" > /dev/null && return 99;
  return 0;
}

function abort {
  echo "$1";
  exit 1;
}

# what adapter should we set up adhoc networking on?
# is there something on the command line?

test -z "$WLAN" && check_wlan_adapter $1 && WLAN=$1;

# can we find it ourselves?

wlanfound=`find_wlan_adapter`;
test -z "$WLAN" && check_wlan_adapter $wlanfound && WLAN=$wlanfound;

# doesn't look good, but let's try 'eth1'
test -z "$WLAN" && check_wlan_adapter eth1 && WLAN=eth1;

# bummer
test -z "$WLAN" && abort "No wlan adapter found!"

WIRE=eth0

MAC="" # set this to spoof mac address

IPADDR=192.168.1.1

# spoof mac address
# ifconfig eth0 hw ether 00:13:CE:ED:DB:1D
# test -z "$MAC" || ifconfig eth0 hw ether "$MAC"

# set up routing (connection sharing)
iptables --table nat --append POSTROUTING --out-interface $WIRE -j MASQUERADE
iptables --append FORWARD --in-interface $WLAN -j ACCEPT

su -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'

echo "Kernel routing set up. Traffic from $WLAN is forwarded to $WIRE"

# set up ad hoc network
iwconfig $WLAN mode ad-hoc essid "$ESSID" channel 10
ifconfig $WLAN $IPADDR up

echo "WLAN ad-hoc networking set up on $WLAN"

# set up dhcp
DNS=$(grep nameserver /etc/resolv.conf | sed 's/^nameserver //');

CONFIGFILE=/tmp/udhcpd.adhoc.$WLAN.conf

cat<<UDHCPD > $CONFIGFILE

# udhcpd config file for adhoc networking
# generated $DATE by $0

interface $WLAN
pidfile /var/run/udhcpd.$WLAN.pid

start 192.168.1.5
end 192.168.1.10

opt dns $DNS
opt router $IPADDR

UDHCPD

/usr/sbin/udhcpd $CONFIGFILE # start udhcpd

echo "DHCP services set up on $WLAN" 


echo "You are now ready to share your internet connection on $WIRE with another computer connecting to $WLAN"
echo "This is what the other computer must know:"
echo ESSID: $ESSID
echo Netmask: 255.255.255.0
echo Gateway/Router: $IPADDR
echo "Nameserver(s)/DNS: $DNS"
