#!/bin/bash
[% c("var/set_default_env") -%]
[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
assets_dir=assets
ext_dir=$assets_dir/extensions
qa_apk=[% dest_dir %]/[% c('filename') %]/[% c("var/project-name") %]-[% c("version") %]-[% c("var/osname") %]-multi-qa.apk
apk=$rootdir/fenix/app-[% c("var/abi") %]-*.apk
test_out_apk=[% dest_dir %]/[% c('filename') %]/[% c("var/project-name") %]-[% c("version") %]-[% c("var/osname") %]-androidTest.apk
test_in_apk=$rootdir/fenix/app-*-androidTest.apk

tar xavf $rootdir/[% c('input_files_by_name/fenix') %]

# Bundle our extensioni(s).
# NoScript will be copied over to the profile folder
# as a "regular" browser extension receiving regular AMO updates.
noscript_path="$ext_dir/{73a6fe31-595d-460b-a920-fcc0f8843232}.xpi"

mkdir -p /var/tmp/build/$ext_dir [% dest_dir _ '/' _ c('filename') %]
cd /var/tmp/build
mv $rootdir/[% c('input_files_by_name/noscript') %] "$noscript_path"

[% IF c("var/verify_allowed_addons") %]
  # Check that allowed_addons.json contains the right versions of our bundled extension(s).
  # If so, replace the default allowed_addons.json by ours in the apk assets folder.
  $rootdir/verify_allowed_addons.py "$rootdir/allowed_addons.json" "$noscript_path"
[% END %]

mv $rootdir/allowed_addons.json $assets_dir/allowed_addons.json

[% c('zip', {
        zip_src => [ '$assets_dir' ],
        zip_args => '$apk',
    }) %]

aligned_apk=$(basename $apk .apk)_aligned.apk
zipalign -vp 4 $apk $aligned_apk

# Sign a QA build. This .apk is not a debug version and doesn't contain a debug
# flag in the manifest.
apksigner sign --verbose --min-sdk-version [% c("var/android_min_api") %] --ks $rootdir/android-qa.keystore --out $qa_apk --in $aligned_apk --ks-key-alias androidqakey --key-pass pass:android --ks-pass pass:android

apksigner sign --verbose --min-sdk-version [% c("var/android_min_api") %] --ks $rootdir/android-qa.keystore --out $test_out_apk --in $test_in_apk  --ks-key-alias androidqakey --key-pass pass:android --ks-pass pass:android

[%IF c("var/tor-browser") -%]
  tor_expert_bundle_src="[% c("input_files_by_name/tor-expert-bundle") %]"
  # strip off trailing "$buildid.tar.gz"
  tor_expert_bundle_dest=${tor_expert_bundle_src:0:-14}.tar.gz
  cp $rootdir/$tor_expert_bundle_src [% dest_dir %]/[% c('filename') %]/$tor_expert_bundle_dest
[% END -%]
