# Maintainer: RafaĹ‚ Brzegowy <rafal.brzegowy@yahoo.com>

_realname=calculix-ccx
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.22
pkgrel=4
pkgdesc="CalculiX: 3D Structural Finite Element Program - Solver (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="http://www.calculix.de/"
license=('spdx:GPL-2.0-or-later')
depends=("${MINGW_PACKAGE_PREFIX}-arpack"
         "${MINGW_PACKAGE_PREFIX}-arpack64"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread"
         "${MINGW_PACKAGE_PREFIX}-omp"
         "${MINGW_PACKAGE_PREFIX}-openblas"
         "${MINGW_PACKAGE_PREFIX}-openblas64"
         "${MINGW_PACKAGE_PREFIX}-pastix"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"))
makedepends=("${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-spooles"
             "${MINGW_PACKAGE_PREFIX}-pkgconf")
source=("http://www.dhondt.de/ccx_${pkgver}.src.tar.bz2"
        "http://www.dhondt.de/gpl-2.0.txt"
        "ccx_mingw.patch"
        "ccx_ooc.patch"
        "ccx_numeric_format.patch"
        "ccx_adapt_main_pastix.patch")
sha256sums=('3a94dcc775a31f570229734b341d6b06301ebdc759863df901c8b9bf1854c0bc'
            '8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643'
            'd85b176778749afa352c926d0c788906dc7d75bb0fa9dd977d5f23bfbe6812b0'
            'dd81df3de137a05b45e39fe61830337e6405ec566148598dab2828a6d9780e8a'
            '48323c6fb59b4af34b75be23819848b782fc1cb0428189d9545ed66d6a1bc10e'
            '04db3443e3f199162cdfa4458a190dd660831a573b39a049bfe1156cca0be404')

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

prepare() {
  cd "${srcdir}/CalculiX/ccx_${pkgver}/src"
  apply_patch_with_msg \
   ccx_mingw.patch \
   ccx_ooc.patch \
   ccx_numeric_format.patch \
   ccx_adapt_main_pastix.patch
}

build() {
  cd "${srcdir}/CalculiX/ccx_${pkgver}/src"

  if [[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]]; then
    CFLAGS+=" -fopenmp -Wno-incompatible-pointer-types -Wno-implicit-function-declaration"
    FC=gfortran
    export FFLAGS="-fallow-argument-mismatch -fopenmp -O2"
    export OMP_LIBS="-lgomp -lquadmath"
  else
    CFLAGS+=" -fopenmp -Wno-implicit-function-declaration"
    FC=flang
    export FFLAGS="-fopenmp -O2 -I${MINGW_PREFIX}/include"
    export OMP_LIBS="-lomp"
  fi

  make CC=${CC} FC=${FC} CCX_VERSION=${pkgver} -f Makefile_mingw_i4
  make CC=${CC} FC=${FC} CCX_VERSION=${pkgver} -f Makefile_mingw_i8
}

package()
{
  install -Dm755 "${srcdir}"/CalculiX/ccx_${pkgver}/src/ccx_i4/ccx_i4.exe "${pkgdir}"${MINGW_PREFIX}/bin/ccx.exe
  install -Dm755 "${srcdir}"/CalculiX/ccx_${pkgver}/src/ccx_i8/ccx_i8.exe "${pkgdir}"${MINGW_PREFIX}/bin/ccx_i8.exe

  install -Dm755 "${srcdir}"/gpl-2.0.txt "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
