# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Martell Malone <martellmalone@gmail.com>

_realname=binutils
_mingw_suff=mingw-w64-cross
pkgname=("${_mingw_suff}-${_realname}")
pkgver=2.42
pkgrel=1
pkgdesc="A set of programs to assemble and manipulate binary and object files"
arch=('i686' 'x86_64')
url="https://www.gnu.org/software/binutils/"
license=('GPL')
groups=("${_mingw_suff}-toolchain" "${_mingw_suff}")
depends=("libiconv" "zlib" "libzstd")
checkdepends=('dejagnu' 'bc')
makedepends=("libiconv-devel" "zlib-devel" 'autotools' 'gcc' 'libzstd-devel')
options=('staticlibs' '!distcc' '!ccache' '!buildflags')
source=(https://ftp.gnu.org/gnu/binutils/binutils-${pkgver}.tar.xz{,.sig}
        0002-check-for-unusual-file-harder.patch
        0010-bfd-Increase-_bfd_coff_max_nscns-to-65279.patch)
sha256sums=('f6e4d41fd5fc778b06b7891457b3620da5ecea1006c6a4a41ae998109f85a800'
            'SKIP'
            '2c99345fc575c3a060d6677537f636c6c4154fac0fde508070f3b6296c1060d4'
            '4e8ac055df61b1b5d6ae29dc87e1154737c2e87c7b244b44866702cabf1a5d18')
validpgpkeys=('EAF1C276A747E9ED86210CBAC3126D3B4AE55E93'
              '3A24BC1E8FB409FA9F14371813FCEF89DD9E3C4F')
msys2_references=(
  'archlinux: binutils'
)

_targets="x86_64-w64-mingw32ucrt i686-w64-mingw32 x86_64-w64-mingw32"

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -p1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd ${srcdir}/binutils-${pkgver}

  apply_patch_with_msg \
    0002-check-for-unusual-file-harder.patch \
    0010-bfd-Increase-_bfd_coff_max_nscns-to-65279.patch
}

build() {
  for _target in ${_targets}; do
    mkdir -p ${srcdir}/binutils-build-${_target} && cd ${srcdir}/binutils-build-${_target}

    local _conf='--enable-lto'

    if [ "${_target}" != "i686-w64-mingw32" ]; then
     _conf+=' --enable-64-bit-bfd'
    fi

    MSYSTEM=CYGWIN
    local CYGWIN_CHOST="${CHOST/-msys/-cygwin}"
    ${srcdir}/binutils-${pkgver}/configure \
      --build=${CYGWIN_CHOST} \
      --host=${CYGWIN_CHOST} \
      --target=${_target} \
      --prefix=/opt \
      --disable-werror \
      --with-libiconv-prefix=/usr \
      --with-system-zlib \
      $_conf

    make
  done
}

check() {
  for _target in ${_targets}; do
    cd ${srcdir}/binutils-build-${_target}

    # unset LDFLAGS as testsuite makes assumptions about which ones are active
    # do not abort on errors - manually check log files
    make LDFLAGS="" -k check || true
  done
}

package() {
  for _target in ${_targets}; do
    cd ${srcdir}/binutils-build-${_target}
    make DESTDIR=${pkgdir} install
  done
}
