#!/bin/sh

echo "Downloading rt73.ko module from ftp://ftp.embeddedarm.com"
wget ftp://ftp.embeddedarm.com/ts-arm-sbc/ts-7500-linux/binaries/wifi/lib/rt73/ts73_ts7500.ko

DIR="/lib/modules/2.6.24.4/kernel/drivers/net/wireless/"

echo -n "Moving rt73 driver to $DIR... "
mv rt73_ts7500.ko $DIR/rt73.ko
echo "done"

# Remove conflicting rt2x00 driver
rm -rf $DIR/rt2x00 

echo -n "Adding rt73 module to /etc/modules for auto load on startup... "
# Remove rt73 from list first just in case user ran script before
sed -i 's/rt73//g' /etc/modules 
echo "rt73" >> /etc/modules
sed -i '/^$/d' /etc/modules
echo "done"


# Copy necessary wpa_supplicant files

wget ftp://ftp.embeddedarm.com/ts-arm-sbc/ts-7500-linux/binaries/wifi/bin/wpa_rt73/wpa_passphrase
wget ftp://ftp.embeddedarm.com/ts-arm-sbc/ts-7500-linux/binaries/wifi/bin/wpa_rt73/wpa_supplicant

echo "Running wpa_supplicant installation script"
SUPP=`which wpa_supplicant`
PASS=`which wpa_passphrase`

if [ $SUPP ]; then
   echo "Existing wpa_supplicant files found at"
   echo "   $SUPP"
   echo "   $PASS"
   echo "Creating backups with .bak extension at"
   echo "   $SUPP.bak"
   echo "   $SUPP.bak"
   mv $SUPP $SUPP.bak
   mv $PASS $PASS.bak

   echo -n "Copying correct wpa_supplicant files... "
   mv wpa_supplicant $SUPP
   mv wpa_passphrase $PASS

else
   echo -n "Copying new wpa_supplicant files to /usr/local/bin... "
   mv wpa_supplicant /usr/local/bin/
   mv wpa_passphrase /usr/local/bin/

fi
echo "done"

# Build module dependencies and install module
echo -n "Inserting rt73.ko module using modprobe... "
depmod -a
modprobe rt73
if [ $? -eq 0 ]; then
   echo "done"
   echo
   echo "The rt73 wireless driver permanently installed."
   echo "Please refer to Linux documentation for setting up"
   echo "your network using /etc/interfaces/network config file."
   echo
else
   echo
   echo "Modprobe failed.  You may need to install manually."
   echo
fi
