#!/bin/sh
# USAGE: ifup-ap <wlan-dev> <wlan-prof>
# Read [AP] section of $HOME/.cerevo.ini,
# Overwrite the profile named <wlan-prof> of /etc/network/interfaces,
# and exec ifup <wlan-dev>=<wlan-prof>

iface_extract () { awk '/^ *iface/{x=0}/^ *iface +'$1'/{x=1}(x){print}';  }
iface_exclude () { awk '/^ *iface/{x=0}/^ *iface +'$1'/{x=1}(!x){print}'; }
probe_netdev () { [ -e /sys/class/net/$1 ]; }

cd /etc/network
trap 'rm /tmp/if-lock' INT TERM EXIT
while ! ln -s / /tmp/if-lock 2> /dev/null; do sleep .2; done
for i in rt5572sta; do rmmod $i; done
for i in rtutil5572ap rt5572ap rtnet5572ap; do insmod /lib/modules/$i.ko; done
modprobe musb_hdrc
i=0
while ! probe_netdev ra0; do
	[ $i -eq 2 ] && exit 3
	sleep 1
	i=$((i+1))
done
iface_exclude $2 < interfaces > i
ifconfig $1 0.0.0.0
NETDEV=$1 autowifi $2 -ap | iface_extract $2 > /tmp/ifup-ap
cat /tmp/ifup-ap >> i
mv i interfaces
sync
rm /tmp/if-lock
trap - INT TERM EXIT
a=$(sed -ne '/^[	 ]*address/{s/.*address[	 ]*\(.*\)/\1/;p;}' < /tmp/ifup-ap)
m=$(sed -ne '/^[	 ]*netmask/{s/.*netmask[	 ]*\(.*\)/\1/;p;}' < /tmp/ifup-ap)
b=${a##*.}
a=${a%.*}
c=$((b+4))
[ $c -ge 255 ] && c=254
cat > /tmp/udhcpd.conf <<EOF
start $a.$((b+1))
end $a.$c
max_leases 4
lease_file /tmp/udhcpd.leases
interface $1
opt subnet $m
opt router $a.$b
opt dns 8.8.8.8 8.8.4.4
EOF
ifup $1=$2
iwpriv $1 set Debug=0 1>&2
ifconfig $1 | grep -q 'inet addr' || exit 1
