#!/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/prev_rust') %]
cd /var/tmp/dist/rust-[% c('var/prev_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/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 $BASEDIR/MacOSX10.11.sdk/ -Wl,-syslibroot,$BASEDIR/MacOSX10.11.sdk/ -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

# LLVM has reproducibility issues when optimizing bitcode, which we need to
# patch. See: #32053 for more details.
cd src/llvm-project
patch -p1 < $rootdir/43909.patch
cd ../../

[% IF c("var/windows-i686") %]
  # Cross-compiling for Windows 32bit is currently not possible without any
  # patches. The reason for that is libstd expecting DWARF unwinding while most
  # toolchains on Linux, targeting Windows 32bit, use SjLj unwinding.
  # See: https://github.com/rust-lang/rust/issues/12859 for discussion about
  # that and https://github.com/rust-lang/rust/pull/49633 for a newer attempt to
  # fix this problem. We apply the patch from neersighted.
  patch -p1 < $rootdir/unwind.patch
[% END %]

mkdir build
cd build
../configure --prefix=$distdir [% 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'),
        }) %]
