#!/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/plugins-release/* $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 /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz

cd /var/tmp/build/[% project %]-[% c('version') %]

# Replace pre-packaged tor library with the latest build
rm -fR service/src/main/jniLibs/*
tar -C service/src/main -xf $rootdir/[% c('input_files_by_name/tor') %]/tor.tar.gz

# Patch native build. Then remove native files, otherwise build will fail after gradle.patch
patch -p1 < $rootdir/remove-native-build.patch
rm -fR service/src/main/jni

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

# Build Android Libraries and Apps
$GRADLE_HOME/gradle-4.10.2/bin/gradle --offline --no-daemon -P androidplugin=3.1.0 -P appcompatVersion=28.0.0 -P compileVersion=28 -P targetVersion=28 -P minVersion=16 -Dmaven.repo.local=$gradle_repo assembleRelease -x lint

# Package
cp jsocksAndroid/build/outputs/aar/* service/build/outputs/aar/* $output_dir
