#!/bin/sh
set -e
rootdir=$(pwd)
distdir=/var/tmp/dist/binutils
[% IF c("var/linux") %]
  # Config options for hardening-wrapper
  export DEB_BUILD_HARDENING=1
  export DEB_BUILD_HARDENING_STACKPROTECTOR=1
  export DEB_BUILD_HARDENING_FORTIFY=1
  export DEB_BUILD_HARDENING_FORMAT=1
  export DEB_BUILD_HARDENING_PIE=1

  # The libstdc++ shipped by default is non-PIC which breaks the binutils build
  # if we build with DEB_BUILD_HARDENING_PIE=1. We need to install a PIC one AND
  # make sure it gets used before the non-PIC one would.
  ln -s /usr/lib/gcc/x86_64-linux-gnu/4.7/libstdc++_pic.a libstdc++.a
  export LDFLAGS="-L$rootdir -lstdc++"
[% END %]
tar xf [% project %]-[% c("version") %].tar.bz2
cd [% project %]-[% c("version") %]
[% IF c('var/windows') -%]
# XXX: This is needed due to bug 10102.
sed 's/= extern_rt_rel_d;/= extern_rt_rel_d;\n  memset (extern_rt_rel_d, 0, PE_IDATA5_SIZE);/' -i ld/pe-dll.c
# Needed for the hardening...
patch -p1 < ../enable-reloc-section-ld.patch
# specify-timestamp patch from Stephen Kitt <steve@sk2.org>
# https://anonscm.debian.org/cgit/collab-maint/binutils-mingw-w64.git/
patch -p2 < ../specify-timestamp.patch
[% END -%]
./configure --prefix=$distdir [% c('var/configure_opt') %]
make -j4
make install

[% IF c("var/linux") %]
# Make sure gold is used with the hardening wrapper for full RELRO, see #13031.
cd $distdir/bin
rm ld
cp /usr/bin/hardened-ld ./
mv ld.gold ld.gold.real
ln -sf hardened-ld ld.gold
ln -sf ld.gold ld
[% END %]

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