#!/bin/bash
[% c("var/set_default_env") -%]
output_dir=[% dest_dir %]/[% c('filename') %]
gradle_repo=$rootdir/[% c('input_files_by_name/gradle-dependencies') %]

# The download script assumes artifact package name is the complete URL path.
# In some cases this is incorrect, so copy those artifacts to correct location
cp -r $gradle_repo/guardianproject/gpmaven/master/* $gradle_repo
cp -r $gradle_repo/dl/android/maven2/* $gradle_repo
cp -r $gradle_repo/maven2/* $gradle_repo
cp -r $gradle_repo/plugins-release/* $gradle_repo

mkdir -p /var/tmp/build $output_dir

[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz

# Patch projects
cd /var/tmp/build/[% project %]-[% c('version') %]
# Gradle patch provided so that when generating a gradle dependency list, the
# build will pull down the correct android tool versions
patch -p1 < $rootdir/gradle.patch
patch -p1 < $rootdir/0001-Bug-33931-Filter-bridges-in-stream-by-type.patch
patch -p1 < $rootdir/0001-Bug-30318-Add-snowflake-support.patch

[% FOREACH arch = ['armv7', 'aarch64', 'x86', 'x86_64'] -%]
  # Extract obfs4proxy from TorBrowser/Tor/PluggableTransports/obfs4proxy
  tar --strip-components=4 -xf $rootdir/[% c('input_files_by_name/obfs4-' _ arch) %]

  # Extract snowflake from TorBrowser/Tor/PluggableTransports/snowflake
  tar --strip-components=4 -xf $rootdir/[% c('input_files_by_name/snowflake-' _ arch) %]

  # Overwrite the obfs4proxy binary provided by Pluto and add Snowflake
  [% IF arch == "armv7" -%]
    cp obfs4proxy external/pluto/bin/armeabi-v7a/
    cp obfs4proxy external/pluto/bin/armeabi/
    cp snowflake-client external/pluto/bin/armeabi-v7a/
    cp snowflake-client external/pluto/bin/armeabi/
  [% ELSIF arch == "aarch64" -%]
    cp obfs4proxy external/pluto/bin/arm64-v8a/
    cp snowflake-client external/pluto/bin/arm64-v8a/
  [% ELSE -%]
    cp obfs4proxy external/pluto/bin/[% arch %]/
    cp snowflake-client external/pluto/bin/[% arch %]/
  [% END -%]

  rm obfs4proxy
  rm snowflake-client
[% END -%]

# Build Android Libraries and Apps
gradle --offline --no-daemon -P androidplugin=3.6.0 -Dmaven.repo.local=$gradle_repo assembleRelease -x lint

# Package
cp universal/build/libs/* android/build/outputs/aar/* $output_dir
