#!/bin/sh

mozapp=$1
mozver=$2
download=1

if [ -z "$mozapp" -o -z "$mozver" ]; then
    echo "usage: $0 <mozilla application> <version>"
fi

case "$mozapp" in
    firefox)
	sourceforgedir="portableapps/Mozilla Firefox, Portable Ed./Mozilla Firefox, Portable Edition $mozver"
	installername=FirefoxPortable
	portablename=FirefoxPortable
	;;
    thunderbird)
	sourceforgedir="portableapps/Mozilla Thunderbird, P.E./Mozilla Thunderbird, Portable Edition $mozver"
	installername=ThunderbirdPortable
	portablename=ThunderbirdPortable
	;;
    *)
	echo "invalid application: $mozapp"
	exit 1
	;;
esac

installer="${installername}_${mozver}_English.paf.exe"
switchlocaleurl=https://addons.mozilla.org/en-US/firefox/downloads/file/16920/locale_switcher-2.1-fx+tb.xpi
switchlocalename=$(basename $switchlocaleurl)

if [ -n "$download" ]; then

    wget -nc "http://freefr.dl.sourceforge.net/sourceforge/$sourceforgedir/$installer"
    wget -nc $switchlocaleurl/$switchlocalename
fi

xpi_url=http://releases.mozilla.org/pub/mozilla.org/$mozapp/releases/$mozver/win32/xpi/
xpi_dir="${mozapp}-${mozver}-xpi"
extdir="${portablename}/App/DefaultData/profile/extensions"

if [ -n "$download" ]; then
    rm -rf $xpi_dir
    mkdir -p $xpi_dir
    lftp -e "lcd $xpi_dir; mget -c *.xpi; quit" $xpi_url
fi

wine $installer

bindir=$(dirname $0)
for ext in $switchlocalename $xpi_dir/*.xpi; do
    $bindir/install-mozilla-extension.sh $extdir $ext
done

mozexe="$portablename/$portablename.exe"
#- pre-create profile data, takes a long time on USB
wine $mozexe
# FIXME: run from key? (different path)
