#!/bin/sh
#
# install_bcm43xx_firmware
#
# This script tries to download and install the firmware needed to run
# WLAN cards using Broadcom's bcm43xx chips.
DIRECT_URL=http://downloads.openwrt.org/sources
DIRECT_FILE=wl_apsta-3.130.20.0.o
URL2=http://www.buffalo-technology.com/downloads
FILE2=WLI2-PCI-G54S.zip

die()
{
    popd
    test -d $TMPDIR
    rm -rf $TMPDIR
    exit 1
}

test -z "$( type -p curl)" && { echo "'curl' is not installed, aborting"; exit 1; }
test -z "$( type -p unzip)" && { echo "'unzip' is not installed, aborting"; exit 1; }
test -z "$( type -p bcm43xx-fwcutter)" && \
	{ echo "'bcm43xx-fwcutter' is not installed, aborting"; exit 1; }
test -d /lib/firmware || mkdir -p /lib/firmware

TMPDIR=$(mktemp -d /var/tmp/bcm.XXXXXX) || exit 1

pushd `pwd` >/dev/null
cd $TMPDIR
echo "Downloading firmware"
curl -# -f -o $DIRECT_FILE $DIRECT_URL/$DIRECT_FILE
if [ $? -eq 0 ];then
	echo "Extracting firmware"
	bcm43xx-fwcutter $DIRECT_FILE
else
	echo "Downloading firmware (alternative file)"
	curl -# -f -o $FILE2 $URL2/$FILE2 || die
	echo "Extracting firmware"
	unzip $FILE2 >/dev/null || die
	bcm43xx-fwcutter CBG54/WIN2000/BCMWL5.SYS
fi
echo -n "Installing firmware"
mv *fw /lib/firmware/ || die
echo
echo "Firmware successfully installed."

popd >/dev/null
rm -rf $TMPDIR

exit 0
