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

# 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

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') %]
for p in $rootdir/*.patch
  do patch -p1 < $p
done

# Use Orbot's PT capabilities
[% IF c("var/android-armv7") %]
  arch=armeabi-v7a
[% ELSE %]
  arch=x86
[% END %]
obfs4dir=orbotservice/src/main/libs/$arch
mkdir -p $obfs4dir
mv external/pluto/bin/$arch/obfs4proxy $obfs4dir/obfs4proxy.so

# Build Android Libraries and Apps
$GRADLE_HOME/gradle-4.1/bin/gradle --offline assembleRelease -x lint

# Package
cp app/build/outputs/aar/* $output_dir
cp orbotservice/build/outputs/aar/* $output_dir
cp jsocksAndroid/build/outputs/aar/* $output_dir
