#!/bin/bash
[% c("var/set_default_env") -%]
distdir=/var/tmp/dist
builddir=/var/tmp/build/[% project %]
mkdir -p $distdir/[% project %]
tar -C $distdir -xf $rootdir/[% c('input_files_by_name/rust') %]
export PATH="/var/tmp/dist/rust/bin:$PATH"
mkdir -p /var/tmp/build
tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz

# Now prepare the offline build
# Move the directory for hardcoding the path in .cargo/config
mv /var/tmp/build/[% project %]-[% c('version') %] $builddir
tar -C $builddir -xjf uniffi-rs-vendor-[% c('version') %].tar.bz2
cd $builddir
mkdir .cargo
cat > .cargo/config << 'EOF'
[source.crates-io]
replace-with = "vendored-sources"

[source.vendored-sources]
directory = "/var/tmp/build/uniffi-rs/vendor"
EOF

# We change the data type of the `all_known_types` Set from HashSet to BTreeSet.
# Uniffi iterates over the elements of this set, and iteration over a HashSet occurs
# in an arbitrary order, while iteration over a BTreeSet orders in a defined (and
# deterministic) order. This patch solves a build reproducibility issue, see
# tor-browser-build#40208.
#
# Upstream bug: https://github.com/mozilla/uniffi-rs/issues/374
patch -p1 < $rootdir/btreeset.patch
# We usually use --frozen but there is no Cargo.lock file available. Thus resort
# to --offline.
cargo build --release --offline --target x86_64-unknown-linux-gnu
mv target/x86_64-unknown-linux-gnu/release/uniffi-bindgen $distdir/[% project %]

cd $distdir
[% c('tar', {
        tar_src => [ project ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
    }) %]
