#!/bin/bash
[% c("var/set_default_env") -%]
distdir=/var/tmp/dist/[% project %]
mkdir -p $distdir
tar -C /var/tmp/dist -xf [% c('input_files_by_name/cmake') %]
export PATH="/var/tmp/dist/cmake/bin:$PATH"
tar -C /var/tmp/dist -xf [% c('input_files_by_name/ninja') %]
export PATH=/var/tmp/dist/ninja:$PATH
tar -C /var/tmp/dist -xf [% c('input_files_by_name/previous_rust') %]
cd /var/tmp/dist/rust-[% c('var/previous_version') %]-x86_64-unknown-linux-gnu
./install.sh --prefix=$distdir-rust-old
export PATH="$distdir-rust-old/bin:$PATH"

[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
[% IF c("var/linux") -%]
  [% pc('python', 'var/setup', { python_tarfile => c('input_files_by_name/python') }) %]
[% END -%]

[% IF c("var/osx") %]
  # We need to clear `CC` and `LDFLAGS` as they are used for the host platform
  # (i.e. Linux).
  unset CC
  unset LDFLAGS

  mkdir $distdir/helper
  # We need to adapt our CFLAGS and make sure our flags are passed down to all
  # dependencies. Using `CFLAGS_x86_apple-darwin` did not do the trick, so resort
  # to a wrapper script.
  cat > $distdir/helper/x86_64-apple-darwin-clang << 'EOF'
#!/bin/sh
BASEDIR=/var/tmp/dist/macosx-toolchain
$BASEDIR/cctools/bin/x86_64-apple-darwin-clang -target x86_64-apple-darwin -B $BASEDIR/cctools/bin -isysroot $sysrootdir -Wl,-syslibroot,$sysrootdir -Wl,-dead_strip -Wl,-pie "$@"
EOF

  chmod +x $distdir/helper/x86_64-apple-darwin-clang
  export PATH=$distdir/helper:$PATH
[% END %]

cd $rootdir
mkdir /var/tmp/build
tar -C /var/tmp/build -xf  [% c('input_files_by_name/rust') %]
cd /var/tmp/build/rustc-[% c('version') %]-src

# Patches for fixing:
#  https://github.com/rust-lang/rust/issues/86436
#  https://github.com/rust-lang/rust/pull/86568
#  https://github.com/rust-lang/rust/issues/86999
# This can be removed when updating to >= 1.54.0.
patch -p1 < $rootdir/fix-build-1.53.0.patch

mkdir build
cd build
../configure --prefix=$distdir --disable-docs --disable-compiler-docs [% c("var/configure_opt") %]

make -j[% c("buildconf/num_procs") %]
make install
cd /var/tmp/dist
[% c('tar', {
        tar_src => [ project ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
        }) %]
