#!/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/dl/android/maven2/* $gradle_repo
cp -r $gradle_repo/maven2/* $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 $GRADLE_HOME -xf $rootdir/[% c('input_files_by_name/gradle') %]
tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz
unzip -d $rootdir $rootdir/[% c('input_files_by_name/jetifier') %]

cd /var/tmp/build/[% project %]-[% c('version') %]
# Replace pre-packaged tor library with the latest build
rm -fR service/src/main/jniLibs/*
[% FOREACH arch = ['armv7', 'aarch64', 'x86', 'x86_64'] -%]
  tar -C service/src/main -xf $rootdir/[% c('input_files_by_name/tor-' _ arch) %]/tor.tar.gz
[% END -%]

# Replace libraries with the config dependencies
rm service/libs/*
cp $rootdir/[% c('input_files_by_name/topl') %]/*{.aar,.jar} service/libs/

# Update bridges list
cat $rootdir/bridges_list.obfs4.txt $rootdir/bridges_list.meek-azure.txt \
  $rootdir/bridges_list.snowflake.txt > service/src/main/assets/common/bridges.txt

# Build Android Libraries and Apps
gradle --offline --no-daemon -P androidplugin=3.6.0 -P appcompatVersion=28.0.0 -P compileVersion=29 -P targetVersion=29 -P minVersion=16 -Dmaven.repo.local=$gradle_repo assembleRelease -x lint

# Bug 40398: Manually jetify each archive and save it in $output_dir
for aar in jsocksAndroid/build/outputs/aar/* service/build/outputs/aar/*; do
  fn=`basename $aar`
  $rootdir/jetifier-standalone/bin/jetifier-standalone -l info -i $aar -o $output_dir/$fn
done
