#!/bin/bash

# script to check for new versions of a package from filehippo.com
# NOTE: If you call this for multiple packages, PLEASE put a delay (5-10 seconds)
# between each call so that you don't over-stress the server!

if [ -z "$1" ]; then
  echo "Downloads the latest version of a package from filehippo.com."
  echo
  echo "Usage: $0 <package name>"
  echo
  echo "  where <package name> is the name of the filehippo.com package."
  echo
  echo "Example, URL for Mozilla Firefox is http://www.filehippo.com/download_firefox/"
  echo "so package name is part of the URL after \"download_\", or \"firefox\"."
  exit 1
fi

PACKAGE=$1
BASEURL=http://www.filehippo.com
URL=$BASEURL/download_$PACKAGE
TEMPFILE=/tmp/$PACKAGE.html
EXEDIR="."
XMLDIR="."

WGET="wget"
AWK="awk"
AGENT="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 1.8.1) Gecko/20061010 Firefox/2.0"
WGETOPTIONS="-t 0 -T 300"

$WGET $WGETOPTIONS -U "$AGENT" -O $TEMPFILE --header="Cookie: Filter=NOBETA=1&NODEMO=0" $URL
NEWVERSION=`grep "<h1>" $TEMPFILE | $AWK 'BEGIN { FS=">" } { print $2 }' | $AWK 'BEGIN { FS="<" } { print $1 }'`
DOWNLOADURL1=$BASEURL`grep "<b>Download<br/>Latest Version</b>" $TEMPFILE | $AWK 'BEGIN { FS="\"" } { print $2 }'`

# delay so don't overload the server.
sleep 1

$WGET $WGETOPTIONS -U "$AGENT" -O $TEMPFILE --header="Cookie: Filter=NOBETA=1&NODEMO=0" $DOWNLOADURL1
DOWNLOADURL2=$BASEURL`grep "HTTP-EQUIV=Refresh" $TEMPFILE | $AWK 'BEGIN { FS="=" } { print $4 }' | $AWK 'BEGIN { FS="\"" } { print $1 }'`

echo Current version = $VERSION
echo New Version = $NEWVERSION
echo Download URL = $DOWNLOADURL2

# if the file to download already exists, we are done.
if [ ! -f "$EXEDIR/$NEWVERSION.exe" ]; then
  echo "New version available... downloading..."
  $WGET $WGETOPTIONS -U "$AGENT" -O "$EXEDIR/$NEWVERSION.exe" $DOWNLOADURL2

  # create a new package.xml file

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"\?>

<packages>

<package
   id=\"$PACKAGE\"
   name=\"$NEWVERSION\"
   revision=\"$REVISION\"
   reboot=\"false\"
   priority=\"10\">

   <check type=\"uninstall\" condition=\"exists\" path=\"Mozilla Firefox (1.5)\" />

   <install cmd='\"%SOFTWARE%\\$PACKAGE\\$NEWVERSION.exe\" -ms' />

   <upgrade cmd='\"%SOFTWARE%\\$PACKAGE\\$NEWVERSION.exe\" -ms' />

   <remove cmd='\"%PROGRAMFILES%\\Mozilla Firefox\\uninstall\\uninstall.exe\" -ms' />

</package>

</packages>
" > "$XMLDIR/$PACKAGE.xml"
else
  echo "$EXEDIR/$NEWVERSION.exe exists, so not downloading anything."
fi

# clean up temp file
rm -f $TEMPFILE

# delay so back-to-back calls of thie script don't overload the server.
sleep 10
