#!/usr/bin/env bash -x

# Forked from https://github.com/devtools-html/debugger.html/blob/master/bin/download-firefox-artifact
#
# This looks for a mozilla-central artifact build as a sibling of the
# activity-stream tree.  If it's not there, it creates it.  If it is there, it
# updates it.

# If AS_GIT_BIN_REPO (the git repo from which prepare-mochitests-dev and
# friends will be executed) isn't set in the environment, just use the repo
#  we're running from.
if [ -z ${AS_GIT_BIN_REPO+x} ]; then
  ROOT=`dirname $0`
  AS_GIT_BIN_REPO="../../../../activity-stream"
else
  ROOT=${AS_GIT_BIN_REPO}/bin
fi

# Compute the mozilla-central path based on whether AS_PINE_TEST_DIR is set
# (i.e. whether this script has been called from test-merges.js)
if [ -z ${AS_PINE_TEST_DIR+x} ]; then
  FIREFOX_PATH="$ROOT/../../mozilla-central"
else
  FIREFOX_PATH=${AS_PINE_TEST_DIR}/mozilla-central
fi

# check that mercurial is installed
if [ -z "`command -v hg`" ]; then
  echo >&2 "mercurial is required for mochitests, use 'brew install mercurial' on MacOS";
  exit 1;
fi

if [ -d "$FIREFOX_PATH" ]; then
    # convert path to absolute path
    FIREFOX_PATH=$(cd "$FIREFOX_PATH"; pwd)

    # If we already have Firefox locally, just update it
    cd "$FIREFOX_PATH";

    if [ -n "`hg status`" ]; then
        read -p "There are local changes to Firefox which will be overwritten. Are you sure? [Y/n] " -r
        if [[ $REPLY == "n" ]]; then
            exit 0;
        fi

        hg revert -a
    fi

    hg pull
    hg update -C
else
    echo "Downloading Firefox source code, requires about 10-30min depending on connection"
    hg clone https://hg.mozilla.org/mozilla-central/ "$FIREFOX_PATH"
    # if somebody cancels (ctrl-c) out of the long download don't continue
    exit_code=$?
    if [ $exit_code -ne 0 ]; then
      exit $exit_code
    fi
    cd "$FIREFOX_PATH"

    # Make an artifact build so it builds much faster
    echo "
ac_add_options --enable-artifact-builds
mk_add_options AUTOCLOBBER=1
mk_add_options MOZ_OBJDIR=./objdir-frontend
" > .mozconfig
fi
