#!/bin/sh
# A shell script for Maemo (the Nokia N900).
# Usage: share-wifi [channel]
# Creates an AdHoc WiFi network, starts up a DHCP/DNS server.
# Does not set up routing/NAT because there's no iptables, so you have to
# use e.g. OpenSSH acting as a SOCKS proxy.

# Warning: if you're not running the latest firmware (PR 1.2), you may
# trigger a wifi driver bug that will exhaust memory and make the n900
# extremely slow until it spontaneously reboots:
# https://bugs.maemo.org/show_bug.cgi?id=5712

IFACE=wlan0
ESSID=n900
MYTEMPHOSTNAME=n900
ADDR=10.20.30.1
NETMASK=255.255.255.0
ADDR_MIN=10.20.30.10
ADDR_MAX=10.20.30.126
TEMPHOSTSFILE=/tmp/hosts.extra

CHANNEL=$1

# become root; assumes you've done
#   sudo gainroot
#   echo "user ALL = (ALL) NOPASSWD: ALL" > /etc/sudoers.d/user
#   update-sudoers
# once
if [ `id -u` -ne 0 ]; then
    exec sudo $0 "$@"
fi

# Automatic search for WiFi networks drops our ad-hoc connection
old_search_interval=`gconftool -g /system/osso/connectivity/network_type/search_interval`
trap "gconftool -s /system/osso/connectivity/network_type/search_interval -t int $old_search_interval" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
gconftool -s /system/osso/connectivity/network_type/search_interval -t int 0

# avahi-daemon makes DNS resolution easier; older packages had a bug where
# it failed to start on boot (because it was missing an upstart file)
test -x /etc/init.d/avahi-daemon && /etc/init.d/avahi-daemon start

ifconfig $IFACE down # otherwise iwconfig mode says device busy
iwconfig $IFACE mode ad-hoc
if [ -n "$CHANNEL" ]; then
    echo "using channel $CHANNEL"
    iwconfig $IFACE channel $CHANNEL
    # Unfortunately my directive to use a particular channel seems to be often
    # (but not always) ignored. I've no clue why.
fi
ifconfig $IFACE up # otherwise iwconfig essid times out
iwconfig $IFACE essid $ESSID
ifconfig $IFACE $ADDR netmask $NETMASK up
echo "Sadly, NAT is not supported yet so you'll have to use ssh -D 1080 user@$MYTEMPHOSTNAME and use the SOCKS5 proxy on localhost:1080."
echo "When you want to disconnect, press Ctrl+C."
echo "if you bring up the connection dialog and trigger a wifi search, the system will power down wlan0 and break sharing.  To wake it up, ^c and restart this script."
echo $ADDR $MYTEMPHOSTNAME > $TEMPHOSTSFILE
/usr/sbin/dnsmasq -i $IFACE -a $ADDR -I lo -z -d \
                  -x /var/run/dnsmasq.$IFACE.pid \
                  --dhcp-range=$ADDR_MIN,$ADDR_MAX,6h \
                  --dhcp-option=3,$ADDR \
                  --dhcp-option=6,$ADDR \
                  -H $TEMPHOSTSFILE

