#!/bin/bash
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

set -ex

# The script starts executing as root. We need to change ownership
# of the caches because they are initially owned by root:root. There
# may not be a cache mount/directory on some instances. So create the
# directory if missing.
if [ $(id -u) = 0 ]; then
    mkdir -p /home/worker/workspace
    chown worker:worker /home/worker/hg-shared /home/worker/workspace

    exec sudo -E -u worker ${0} "${@}"
fi

DEST=$1
shift

# We set the base repository to mozilla-central so tc-vcs doesn't get
# confused. Switch to mozilla-unified because robustcheckout works best
# with it.
if [ "${GECKO_BASE_REPOSITORY}" = "https://hg.mozilla.org/mozilla-central" ]; then
    GECKO_BASE_REPOSITORY=https://hg.mozilla.org/mozilla-unified
fi

/usr/bin/hg robustcheckout \
    --sharebase /home/worker/hg-shared \
    --purge \
    --upstream ${GECKO_BASE_REPOSITORY} \
    --revision ${GECKO_HEAD_REV} \
    ${GECKO_HEAD_REPOSITORY} \
    ${DEST}

exec "${@}"
