#!/bin/bash
[% INCLUDE 'build_common' %]

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/clang') %]
export LLVM_CONFIG="/var/tmp/dist/clang-linux/bin/llvm-config"
export PATH="/var/tmp/dist/rust/bin:/var/tmp/dist/cbindgen:/var/tmp/dist/nasm/bin:/var/tmp/dist/clang-linux/bin:$PATH"

[% IF c("var/rlbox") -%]
  tar -C /var/tmp/dist -xf [% c('input_files_by_name/wasi-sysroot') %]
  export WASI_SYSROOT=/var/tmp/dist/wasi-sysroot/
[% END -%]

cd /var/tmp/build/[% project %]-[% c("version") %]
cat > .mozconfig << 'MOZCONFIG_EOF'
. $topsrcdir/mozconfig-[% c("var/osname") %]

mk_add_options MOZ_PARALLEL_BUILD=[% c("num_procs") %]
export MOZ_INCLUDE_SOURCE_INFO=1
export MOZ_SOURCE_REPO="[% c('var/gitlab_project') %]"
export MOZ_SOURCE_CHANGESET=[% c("var/git_commit") %]

ac_add_options --enable-update-channel=[% c("var/variant") %]
MOZCONFIG_EOF
echo "ac_add_options --with-branding=$branding_dir" >> .mozconfig

echo "Starting ./mach configure $(date)"
./mach configure \
  --with-base-browser-version=[% c("var/torbrowser_version") %] \
  [% IF !c("var/rlbox") -%]--without-wasm-sandboxed-libraries[% END %]

echo "Starting ./mach build $(date)"
./mach build --verbose

[% IF c("var/dev_artifacts") -%]
  echo "Building development artifacts"
  ./mach package

  artifactsdir=$outdir/artifacts
  mkdir -p $artifactsdir
  # Copy the artifacts to the target directory
  # Naming convention is the same as Mozilla uses for their artifacts
  cp -a obj-*/dist/*.zip $artifactsdir/target.xpt_artifacts.zip
  cp -a obj-*/gradle/build/mobile/android/geckoview_example/outputs/apk/*/geckoview_example-*.apk $artifactsdir/geckoview_example.apk
  ./mach python -m mozbuild.action.test_archive common $artifactsdir/target.common.tests.tar.gz
[% END %]

echo "Build finished, copying the AAR to the to the destination directory $(date)"

[% IF !c("var/android_single_arch") -%]
  mkdir -p "$outdir/[% project %]"
  # We don't want the debug or "exoplayer" .aars, but the .aar that has `omni` in its name.
  find obj-* -type f -name geckoview*omni*.aar -exec mv {} $outdir/[% project %] \;
[% ELSE -%]
[% INCLUDE 'build_ac_fenix' %]
[% END -%]
