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

mkdir /var/tmp/build
mkdir /var/tmp/dist
cd /var/tmp/dist
tar xf $rootdir/[% c('input_files_by_name/binutils') %]
mv binutils $distdir
export PATH="$distdir/bin:$PATH"

cd /var/tmp/build
tar xf $rootdir/[% project %]-[% c("version") %].tar.gz
mkdir -p builddir/mingw-w64/mingw-w64-headers32
cd builddir/mingw-w64/mingw-w64-headers32
/var/tmp/build/[% project %]-[% c("version") %]/mingw-w64-headers/configure \
                --prefix=$distdir/[% c("arch") %]-w64-mingw32 --host=[% c("arch") %]-w64-mingw32 \
                --enable-sdk=all --enable-idl
make install

cd /var/tmp/build
mkdir gcc
cd gcc
tar xJf $rootdir/gcc-[% c("var/gcc_version") %].tar.xz
# LDFLAGS_FOR_TARGET does not work for some reason. Thus, we take
# CFLAGS_FOR_TARGET.
export CFLAGS_FOR_TARGET="-Wl,--nxcompat -Wl,--dynamicbase -Wl,--no-insert-timestamp [% c('var/flag_noSEH') %]"
# Rust requires enabling pthreads
gcc-[% c("var/gcc_version") %]/configure --prefix=$distdir --target=[% c("arch") %]-w64-mingw32 --with-gnu-ld --with-gnu-as --disable-multilib --enable-threads=posix --enable-languages=c,c++
make -j[% c("buildconf/num_procs") %] all-gcc
make install-gcc

mkdir -p /var/tmp/build/builddir/mingw-w64/mingw-w64-crt32
cd /var/tmp/build/builddir/mingw-w64/mingw-w64-crt32
/var/tmp/build/[% project %]-[% c("version") %]/mingw-w64-crt/configure \
                 --host=[% c("arch") %]-w64-mingw32 --prefix=$distdir/[% c("arch") %]-w64-mingw32
make -j[% c("buildconf/num_procs") %]
make install

mkdir -p /var/tmp/build/builddir/mingw-w64/mingw-w64-pthread
cd /var/tmp/build/builddir/mingw-w64/mingw-w64-pthread
/var/tmp/build/[% project %]-[% c("version") %]/mingw-w64-libraries/winpthreads/configure \
  LDFLAGS="-Wl,--dynamicbase -Wl,--nxcompat -Wl,--enable-reloc-section -Wl,--no-insert-timestamp [% c('var/flag_noSEH') %]" \
  --host=[% c("arch") %]-w64-mingw32 --prefix=$distdir/[% c("arch") %]-w64-mingw32
make -j[% c("buildconf/num_procs") %]
make install

mkdir -p /var/tmp/build/builddir/mingw-w64/widl32
cd /var/tmp/build/builddir/mingw-w64/widl32
/var/tmp/build/[% project %]-[% c("version") %]/mingw-w64-tools/widl/configure \
                 --prefix=$distdir --target=[% c("arch") %]-w64-mingw32
make -j[% c("buildconf/num_procs") %]
make install

cd /var/tmp/build/gcc
make -j[% c("buildconf/num_procs") %]
make install
mkdir -p $distdir/gcclibs
# We compile libssp both for being used dynamically (in tor) and statically (in
# firefox).
cp [% c("arch") %]-w64-mingw32/libssp/.libs/libssp* $distdir/gcclibs
cp [% c("arch") %]-w64-mingw32/libgcc/shlib/[% c("var/libgcc_dll") %] $distdir/gcclibs

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