#!/bin/bash
[% c("var/set_default_env") -%]
distdir=/var/tmp/dist/[% project %]
mkdir -p $distdir

output_dir=[% dest_dir %]/[% c('filename') %]
mkdir -p $output_dir

cd $distdir

tar -xkf $rootdir/[% c('input_files_by_name/tor') %]

cd tor
mkdir pluggable_transports && cd pluggable_transports

function pt_licenses {
  dest=$1
  pushd licenses
  find -type f -printf '%P\n' | sort | while read filename; do
    echo $filename >> $dest
    # https://stackoverflow.com/a/5349796
    printf "%${#filename}s\n" |tr " " "=" >> $dest
    cat $filename >> $dest
    printf "\n\n" >> $dest
  done
  popd
  rm -rf licenses
}

tar -xkf $rootdir/[% c('input_files_by_name/lyrebird') %]
pt_licenses $distdir/docs/lyrebird.txt
[% IF c('input_files_by_name/conjure') -%]
  tar -xkf $rootdir/[% c('input_files_by_name/conjure') %]
  pt_licenses $distdir/docs/conjure.txt
[% END -%]

# add per-platform pt extension
awk '{gsub(/\$\{pt_extension\}/, "[% c("var/pt_extension") %]"); print}' $rootdir/pt_config.json > pt_config.json

cd $distdir

# package a .aar on android
[% IF c("var/android") -%]
  aar_file=torExpertBundle-[% c('arch') %].aar

  abi=[% c('var/abi') %]

  mkdir aar
  mkdir -p aar/jni/$abi
  mkdir -p aar/assets/common

  cp -a tor/libTor.so aar/jni/$abi/
  cp -a tor/pluggable_transports/lyrebird aar/jni/$abi/libLyrebird.so
  [% IF c('input_files_by_name/conjure') -%]
    cp -a tor/pluggable_transports/conjure-client aar/jni/$abi/libConjure.so
  [% END -%]

  # tor-browser-build#41224, tor-browser#42607: Currently we do not use the
  # GeoIP databases. So, we avoid copying them to save space on the final APK.
  # cp -a data/* aar/assets/common/

  cp -a tor/pluggable_transports/pt_config.json aar/assets/common/

  cp -a $rootdir/AndroidManifest.xml aar/

  cd aar
  jar -cvf $output_dir/tor-expert-bundle-[% c('arch') %].aar *
  cd ..
[% END %]

[%
  SET tar_src = [ "tor", "data", "docs" ];
  IF c("var/linux");
   tar_src.push("debug");
  END;
  c('tar', {
    tar_src => tar_src,
    tar_args => '-czvf' _ dest_dir _ '/' _ c('filename') _ '/tor-expert-bundle.tar.gz',
  });
%]
