#!/bin/bash
[% c("var/set_default_env") -%]
[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
distdir=/var/tmp/dist
mkdir -p /var/tmp/build
mkdir -p $distdir/[% project %]

tar -C $GRADLE_HOME -xf $rootdir/[% c('input_files_by_name/gradle') %]

# We need to have the get-moz-build-date script available in the container
# but we can't include it via input_files as it is a script shared between
# projects.
cat > get-moz-build-date << "EOF"
[% INCLUDE "get-moz-build-date" %]
EOF

tar -C /var/tmp/dist -xf [% c('input_files_by_name/rust') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/cbindgen') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/nasm') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/node') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/clang') %]
export LLVM_CONFIG="/var/tmp/dist/clang/bin/llvm-config"
tar -C /var/tmp/dist -xf [% c('input_files_by_name/binutils') %]
export PATH="/var/tmp/dist/rust/bin:/var/tmp/dist/cbindgen:/var/tmp/dist/nasm/bin:/var/tmp/dist/node/bin:/var/tmp/dist/clang/bin:/var/tmp/dist/binutils/bin:$PATH"

tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz

cd /var/tmp/build/[% project %]-[% c("version") %]
mv -f $rootdir/[% c('input_files_by_name/mozconfig') %] .mozconfig

eval $(perl $rootdir/get-moz-build-date [% c("var/copyright_year") %] [% c("var/torbrowser_version") %])
if [ -z $MOZ_BUILD_DATE ]
then
    echo "MOZ_BUILD_DATE is not set"
    exit 1
fi

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64
gradle_repo=/var/tmp/dist/gradle-dependencies
export GRADLE_MAVEN_REPOSITORIES="file://$gradle_repo","file://$gradle_repo/maven2"
export GRADLE_FLAGS="--no-daemon --offline"
# Move the Gradle repo to a hard-coded location. The location is embedded in
# the file chrome/toolkit/content/global/buildconfig.html so it needs to be
# standardized for reproducibility.
mv $rootdir/[% c('input_files_by_name/gradle-dependencies') %] $gradle_repo
cp -r $gradle_repo/m2/* $gradle_repo

rm -f configure
rm -f js/src/configure

# We unbreak mach, see: https://bugzilla.mozilla.org/show_bug.cgi?id=1656993.
export MACH_USE_SYSTEM_PYTHON=1
# Create .mozbuild to avoid interactive prompt in configure
mkdir "$HOME/.mozbuild"
./mach configure --with-tor-browser-version=[% c("var/torbrowser_version") %] --with-java-bin-path="$JAVA_HOME/bin" --without-wasm-sandboxed-libraries
./mach build --verbose

# We don't want to have the debug .aar but the one that has `$channel`, `$arch`,
# and `$version` in its name.
find obj-* -type f -name geckoview-*-*-*.aar -exec cp {} $distdir/[% project %] \;

cd $distdir
[% c('tar', {
        tar_src => [ project ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
    }) %]
