#!/bin/sh

# $Id: /svn/trunk/debian/dists/rt73/debian/scripts/update-rt73-firmware.sh 2424 2007-10-18T20:23:05.445223Z dexter  $
#
# (C) 2006, 2007 Piotr Roszatycki <dexter@debian.org> GPL


set -e

DIR=/etc/firmware
FILE=rt73.bin
URL=http://www.ralinktech.com/ralink/Home/Support/Linux.html


error () {
    echo "E: $1" 1>&2
    echo "E: " 1>&2
    echo "E: Please download firmware RT2501USB(RT2571W/RT2671) from" 1>&2
    echo "E: $URL" 1>&2
    echo "E: and unpack the $FILE file into $DIR." 1>&2
    exit 1
}


TMPDIR=${TMPDIR:-/tmp}
tmpdir="$TMPDIR/update-rt73-firmware-tmpdir"

if [ -d "$DIR" ] && ! [ -w "$DIR" ]; then
    error "Can't write to $DIR directory"
fi

if ! [ -d "$DIR" ]; then
    mkdir -p "$DIR"
fi

rm -rf "$tmpdir"
mkdir -p "$tmpdir"
cd "$tmpdir" || error "Can't create temporary directory $tmpdir"

:> wgetrc
echo "noclobber = off" >> wgetrc
echo "dir_prefix = ." >> wgetrc
echo "dirstruct = off" >> wgetrc
echo "verbose = on" >> wgetrc

WGETRC=wgetrc wget -O"$tmpdir/index.html" $URL || error "Can't download index page"

test -f index.html || error "Can't download index page"

line=`sed 's/<a /\n&/g' "$tmpdir/index.html" | grep '/RT71W_Firmware_V.*\.zip"' || true`

test -z "$line" && error "Can't find firmware location"

url=`echo "$line" | sed 's,.*<a href="\([^"]*/RT71W_Firmware_V[^"]*\)".*,\1,' || true`

test -z "$url" && error "Can't find firmware location"

if [ "$url" = "${url#http://}" ]; then
    url="http://www.ralinktech.com/$url"
fi

WGETRC=wgetrc wget -O"$tmpdir/rt73.zip" "$url" || error "Can't download firmware archive"

unzip -o -d. -j rt73.zip "*/$FILE" || error "Can't unpack firmware file"

chmod 644 $FILE

test -f $FILE || error "Can't unpack firmware file"

printf "\nCopying:\n"
cp -va "$tmpdir/$FILE" "$DIR"

rm -rf "$tmpdir"

if [ ! -f /lib/firmware/rt73.bin ] && [ ! -h /lib/firmware/rt73.bin ]; then
    printf "\nLinking:\n"
    ln -vs /etc/firmware/rt73.bin /lib/firmware/rt73.bin
fi

printf "\nDone.\n" 2>&1

exit 0

cat << POD

# pod2man --name=update-rt73-firmware --section=8 --release="Debian" --center=" " --date="13 Jul 2007"

=head1 NAME

update-rt73-firmware - Download the firmware for Ralink RT73 a/b/g WLAN Card

=head1 SYNOPSIS

B<update-rt73-firmware>

=head1 DESCRIPTION

This utility downloads the latest firmware for Ralink RT73 a/b/g WLAN Card
and places it as F</etc/Wireless/RT73STA/rt73.bin> file.  The utility uses
B<wget>(1) and B<unzip>(1) for downloading and unpacking the firmware image.

=head1 FILES

=over 8

=item F</etc/Wireless/RT73STA/rt73.bin>

contains the firmware image

=head1 BUGS

The script will break if the Ralink website changes dramatically.

=head1 SEE ALSO

B<wget>(1), L<http://www.ralinktech.com/>

=head1 AUTHOR

Copyright (C) 2006, 2007 Piotr Roszatycki E<lt>dexter@debian.orgE<gt>.
