#!/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
builddir=/var/tmp/build/[% project %]
mkdir $distdir/[% project %]
mkdir /var/tmp/build

[% IF !c("var/fetch_gradle_dependencies") %]
  [% pc('python', 'var/setup', { python_tarfile => c('input_files_by_name/python') }) %]
  # XXX: Make this more generic and not only for geckoview-beta.
  geckoview_version=$(find . -type f -name geckoview-beta-*.aar | cut -d \- -f 6 | cut -d \. -f 1-3)
  gradle_repo=$rootdir/[% c('input_files_by_name/gradle-dependencies') %]
  cp -r $gradle_repo/dl/android/maven2/* $gradle_repo
  cp -r $gradle_repo/maven2/* $gradle_repo
  cp -r $gradle_repo/m2/* $gradle_repo
  tar -C $distdir -xf [% c('input_files_by_name/application-services') %]
  # XXX: We could be smarter and just copy over the projects that are needed
  # according to the Gradle dependencies list.
  cp -rf $distdir/application-services/maven/org $gradle_repo
  tar -C $distdir -xf [% c('input_files_by_name/geckoview') %]
[% END %]
tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz

cd $builddir-[% c('version') %]
patch -p1 < $rootdir/git.patch
[% IF c("var/fetch_gradle_dependencies") %]
  # XXX: fetching deps for `assembleGeckoBeta -x lint` by using that same target
  # results in some missing dependencies for yet unknown reasons. Thus, we use
  # `assemble` instead for now.
  gradle --debug -no-daemon assemble
[% ELSE %]
  # Prepare Glean dependencies for offline build
  tar -xjf $rootdir/glean-parser-[% c('var/glean_parser') %].tar.bz2
  # We need to set `LC_ALL` and `LANG` to something that is not ASCII as encoding
  # otherwise `click` barfs. See: https://click.palletsprojects.com/python3/
  export LC_ALL=C.UTF-8
  export LANG=C.UTF-8
  patch -p1 < $rootdir/mavenLocal.patch

  # Make sure our GeckoView dependency is used. XXX: Make this more generic and
  # not only for geckoview-beta.
  cp -f $distdir/geckoview/*.aar $gradle_repo/org/mozilla/geckoview/geckoview-beta/$geckoview_version/geckoview-beta-$geckoview_version.aar

  gradle_args="--offline --no-daemon -Dmaven.repo.local=$gradle_repo"

  gradle $gradle_args assembleGeckoBeta -x lint
  gradle $gradle_args publish

  find components -regex '.*[0-9].\(aar\|pom\)' -exec cp --parents {} $distdir \;

  # Package
  cd $distdir
  find components -type d -name maven -exec cp -rf {} [% project %] \;
  [% c('tar', {
        tar_src => [ project ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
    }) %]
[% END %]
