#!/bin/sh

# Allow calling script to override these defaults
if [ 0$PORTSDIR = 0 ]; then
    PORTSDIR='/usr/ports'
fi

if [ 0$LOADER_CONF = 0 ]; then
    LOADER_CONF='/boot/loader.conf'
fi

if [ 0$RC_CONF = 0 ]; then
    RC_CONF='/etc/rc.conf'
fi

# add wlans_{dev}0="wlan0" to rc.conf
# FIXME: The real solution should detect all wireless devices,
# not just those enumerated here.
start_cwd=`pwd`

cd $PORTSDIR/net
# ipw and iwi are in GENERIC kernel, so don't load their kmods
for port in bwi bwn; do
    cd $port-firmware-kmod
    if ! make -DBATCH install; then
	printf "Failed to install $port-firmware-kmod.\n"
    fi
    cd ..
done

cd $start_cwd
# Check bwi before bwn.  They support the same devices, but
# bwi seems to work better.
drivers="an ath bwi bwn ipw iwi iwn malo mwl ral rum run uath upgt urtw urtwn wpi zyd"

for driver in $drivers; do
    if kldload if_${driver} > /dev/null 2>&1; then
	printf "Loaded $driver.\n"
    fi
done

# FIXME: See what's already configured, don't just start at 0
wlan=0
for driver in $drivers; do
    if grep -q "^${driver}0" /var/run/dmesg.boot || \
	# FIXME: Check also for ${driver}1, ${driver}2, etc.
	# Also could use a better test than this simple grep.
	dmesg | grep -q "^${driver}0"; then
	printf "Found wireless device ${driver}0.\n"
	auto-append-line "wlans_${driver}0" "wlans_${driver}0=\"wlan$wlan\"" $RC_CONF desktop-installer
	# Not necessary for drivers which are in the GENERIC kernel, but
	# it shouldn't hurt.
	auto-append-line "if_${driver}_load=\"YES\"" \
	    "if_${driver}_load=\"YES\"" $LOADER_CONF desktop-installer
	wlan=$(($wlan + 1))
	# break   # Configure only one wireless device!
    fi
done
auto-append-line 'ifconfig_wlan0' 'ifconfig_wlan0="WPA DHCP"' $RC_CONF desktop-installer

