#!/bin/bash

# See Credits at end for more, including some copyright info.

######################################################################
# constants

# Directory to place Firefox download packages under.
# Subdirectories will be created for each version.
FFDIR=/pub/org/Mozilla/Firefox

# Base URL for Firefox distribution redirector.
# Should not need to change, unless Mozilla changes something.
# Do *NOT* include the trailing slash.
FFBASEURL=https://download.mozilla.org

######################################################################
# functions

# ----------------------------------------------------------------------
function die () {
# abort program with message

echo "$0: $*" > /dev/stderr
exit 1

}

# ----------------------------------------------------------------------
function decho () {
# debug echo: only print a message if DEBUG is defined

[ -z "$DEBUG" ] && return
echo "$0: $*" > /dev/stderr

}

######################################################################
# main

# Make sure download directory exists.
[ -d "$FFDIR" ] || die "Bad directory: $FFDIR"

# Get architecture of the machine we are running on.
ARCH="${ARCH:-$(uname -m)}"

# We check the machine architecture for literal string "64".
# If present, we set BITSKLUDGE to "64" to match.
# If not present, we leave BITSKLUDGE unset (empty).
# We use this later to request "linux" or "linux64".
BITSKLUDGE=
echo $ARCH | fgrep -q 64 && BITSKLUDGE=64

# Firefox "OS".  This really means OS+architecture.
# For some reason the download redirector doesn't use the specifiers
# used elsewhere (even elsewhere in Firefox!).  These also match the
# specifiers used in the native OSes, which made things really easy.
# Instead there are a handful of special cases:
#     win, win64, linux, linux64, osx
# We default to Linux, and to the word size we are running on.
FFSYSTEM="${FFSYSTEM:-linux${BITSKLUDGE}}"

# Firefox distribution channel.
# Default to mainstream/consumer.
# Use "latest-esr" for the enterprise channel (Extended Support Release).
FFCHANNEL="${FFCHANNEL:-latest}"

# Firefox language.  Default to English - United States.
FFLANG="${FFLANG:-en-US}"

# Generic Firefox URL.
# This is the URL that will yield the URL of the latest release.
# We just plug in the paramters for the release we want.
FFGENERICURL="$FFBASEURL/?product=firefox-$FFCHANNEL&os=$FFSYSTEM&lang=$FFLANG"
decho "FFGENERICURL=<$FFGENERICURL>"

# Firefox release URL.
# This is the URL of the actual download package/archive.
# We request the generic URL, and get a redirect to the release URL.
# --fail causes curl to return no output on failure, which we test for.
# The combination of --silent, --write-out, and --output cause
#   curl to cough up just the redirect target URL, without HTML adornment.
#   This isn't explictly documented but it works with 7.26.0.
FFURL=$(curl --fail --silent --write-out '%{redirect_url}' --output /dev/null "$FFGENERICURL")
decho "FFURL=<$FFURL>"
[ -n "$FFURL" ] || die "Could not determine the latest Firefox release URL"

# Now we extract the version number from the release URL.
# This is a purely local string manipulation.
FFVERSION=$(echo "$FFURL" | sed -nr 's|.*/firefox-(.*)\.tar\.bz2$|\1|p' )
decho "FFVERSION=<$FFVERSION>"
[ -n "$FFVERSION" ] || die "Could not determine the latest Firefox version"

# Now that we know the version...
# Redefine FFDIR to include the version and arch subdirs.
FFDIR="$FFDIR/$FFVERSION/$FFSYSTEM"
decho "FFDIR=<$FFDIR>"

# If download package already exists, exit silently.
if [ -e "$FFDIR/firefox-$FFVERSION.tar.bz2" ]; then
	decho "Download package already exists, exiting"
	exit
fi

# Package does not exist locally.  Let's download it.
decho "Time to make the donuts."

# Create directory (if needed).
mkdir -p "$FFDIR" || die "mkdir failed: $FFDIR"
[ -d "$FFDIR" ] || die "existance failure: $FFDIR"

# Download the file.
wget --quiet --directory-prefix="$FFDIR" "$FFURL" || die "wget failed: $FFURL"

# That should be it.

######################################################################
# Credits

# Originally based on code from the following:

# latest-firefox Version 1.2
# https://gist.githubusercontent.com/ruario/9672798/raw/ecf8ba455a40d73fa996a7606a0fb8f135990719/latest-firefox
# Retrieved 2015 SEP 09
#
# Copyright 2015 Ruari Oedegaard, Oslo, Norway
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

######################################################################
# END OF FILE
######################################################################

