# Maintainer: J. Peter Mugaas <jpmugaas@suddenlink.net>

_realname=f2c
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=20250303
pkgrel=1
pkgdesc='Fortran to C code translator (mingw-w64)'
url='https://www.netlib.org/f2c/index.html'
license=('custom')
makedepends=('unzip' "${MINGW_PACKAGE_PREFIX}-cc")
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
source=(f2c-src-${pkgver}.tgz::"https://www.netlib.org/f2c/src.tgz"
        libf2c-${pkgver}.zip::"https://www.netlib.org/f2c/libf2c.zip"
        "https://www.netlib.org/f2c/fc"
        20051004-add-ofiles-dep.patch
        20090407-cygwin-build.patch
        libf2c-20110801-64bit-long.patch
        libf2c-1.patch)
noextract=("libf2c-${pkgver}.zip")
sha256sums=('b2824a6f7b75ffe0193ce9ba55463191a7af7c2ffe10e371e372451e2b527e09'
            'cc84253b47b5c036aa1d529332a6c218a39ff71c76974296262b03776f822695'
            'f0dced9b581a5808bd2d0d5e4716997043960a56333d5f4c44b201b870aa0ea8'
            '3f688297b45515c1e386bb7f94ad36bf0f6a3497a0baff759b54d943cbec7d8f'
            '9f689b0dbed2cb47d474ba95235787851fe500c4108ea8e6c4a5eb934da06b0e'
            '919698643f12b2fc4b9f4ebac395a8b2c9c01e83028907621b95dee8db4d5653'
            '49032ffa96961610a1afe878c79bf99feff73a6449e7494ed16213b63cb6043c')

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

prepare() {
  cd "${srcdir}"
  [[ -d f2c ]] && rm -rf f2c
  mv src f2c

  [[ -d libf2c ]] && rm -rf libf2c
  mkdir libf2c
  unzip -q libf2c-${pkgver}.zip -d libf2c

  # mxe patch
  cd "${srcdir}"/libf2c
  apply_patch_with_msg \
    20051004-add-ofiles-dep.patch \
    20090407-cygwin-build.patch \
    libf2c-20110801-64bit-long.patch \
    libf2c-1.patch
}

build() {
  cd "${srcdir}"/libf2c
  make -f makefile.u \
    libf2c.a libf2c.dll.a \
    AR=${MINGW_PREFIX}/bin/ar \
    LD=${MINGW_PREFIX}/bin/ld \
    RANLIB=${MINGW_PREFIX}/bin/ranlib \
    CFLAGS="${CFLAGS} -Wno-implicit-function-declaration -std=gnu89 -DUSE_CLOCK"

  cd "${srcdir}"/f2c
  make f2c -f makefile.u \
    CFLAGS="${CFLAGS} -std=gnu89"
}

package() {
  install -Dm644 fc "${pkgdir}"${MINGW_PREFIX}/bin/fc

  cd "${srcdir}/libf2c"
  install -Dm644 f2c.h "${pkgdir}"${MINGW_PREFIX}/include/f2c.h
  install -Dm644 libf2c-2.dll "${pkgdir}"${MINGW_PREFIX}/bin/libf2c-2.dll
  install -Dm644 libf2c.dll.a "${pkgdir}"${MINGW_PREFIX}/lib/libf2c.dll.a
  install -Dm644 libf2c.a "${pkgdir}"${MINGW_PREFIX}/lib/libf2c.a

  install -Dm755 "${srcdir}"/f2c/f2c.exe "${pkgdir}"${MINGW_PREFIX}/bin/f2c.exe
}
