# Maintainer: Jürgen Pfeifer <juergen@familiepfeifer.de>
# Contributor: Tim S <stahta01@gmail.com>

_realname=gprbuild
pkgbase=mingw-w64-${_realname}
pkgname=${MINGW_PACKAGE_PREFIX}-${_realname}
_gh_release=26.0.0
pkgver=20${_gh_release}
pkgrel=1
pkgdesc="Software tool designed to help automate the construction of multi-language systems (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64')
replaces=("${MINGW_PACKAGE_PREFIX}-gprbuild-gpl")
license=('spdx:GPL-3.0-or-later with GCC-exception-3.1')
url="https://github.com/AdaCore/gprbuild/"
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc-ada"
             "${MINGW_PACKAGE_PREFIX}-xmlada"
             "${MINGW_PACKAGE_PREFIX}-gprbuild-bootstrap-git")
conflicts=("${MINGW_PACKAGE_PREFIX}-gprbuild-bootstrap")
source=("https://github.com/AdaCore/gprbuild/archive/v${_gh_release}/gprbuild-${_gh_release}.tar.gz"
        "https://github.com/AdaCore/gprconfig_kb/archive/v${_gh_release}/gprconfig_kb-${_gh_release}.tar.gz"
        "0001-remove-binder-option.patch")
sha256sums=('4699443c1a97a1527de44e6c3d3505fd95c3904a6533e67cd34c674c408f7d4f'
            'd6edeb941ab9df6b6a186180f17d9a89c57d25be1e0acd8a9237c38164d944de'
            'b3cbf68cdd1e5dfa48ad87a4e0cf85b50cdc806d43380d37026382a9eea58d7b')

prepare() {
  cd "${srcdir}/gprbuild-${_gh_release}/"

  # Apply patch to remove binder -E option. This option makes exception
  # propagation crash with msys2's GNAT.
  patch -p0 -i "${srcdir}/0001-remove-binder-option.patch"

  # GPRbuild hard-codes references to ${MINGW_PREFIX}/libexec, but MINGW packages
  # must use ${MINGW_PREFIX}/lib instead.
  sed -i "s|libexec|lib|g" doinstall gprbuild.gpr \
    "${srcdir}/gprconfig_kb-${_gh_release}/db/compilers.xml" \
    "${srcdir}/gprconfig_kb-${_gh_release}/db/linker.xml" \
    "${srcdir}/gprconfig_kb-${_gh_release}/db/gnat.xml"

  build_date=$(date '+%Y%m%d')
  release_year=$(echo ${pkgver} | cut -d. -f1)

  # Set version information
  sed -i "s/18.0w/${pkgver}/" gpr/src/gpr-version.ads
  sed -i "s/19940713/${build_date}/" gpr/src/gpr-version.ads
  sed -i "s/2016/${release_year}/" gpr/src/gpr-version.ads
  sed -i "s/:= Gnatpro;/:= FSF;/" gpr/src/gpr-version.ads
}

build() {
  [[ -d "${srcdir}"/build-${MSYSTEM} ]] && rm -rf "${srcdir}"/build-${MSYSTEM}
  cp -r "${srcdir}"/gprbuild-${_gh_release} "${srcdir}"/build-${MSYSTEM}
  cd "${srcdir}"/build-${MSYSTEM}

  rm -f makefile.setup

  make SOURCE_DIR="$PWD" prefix="${MINGW_PREFIX}" PROCESSORS="$(nproc)" setup

  make
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  make prefix="${pkgdir}${MINGW_PREFIX}" INSTALL=cp install

  # Copy License Files
  install -Dm644 -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/" COPYING*

  # Copy gprconfig knowledge base
  install -Dm644 -t "${pkgdir}${MINGW_PREFIX}/share/gprconfig" "${srcdir}/gprconfig_kb-${_gh_release}"/db/*
}
