# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=wannier90
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.1.0
pkgrel=1
pkgdesc="The Maximally-Localised Generalised Wannier Functions Code (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='http://www.wannier.org/'
msys2_repository_url="https://github.com/wannier-developers/wannier90"
msys2_references=(
  'aur: wannier90'
)
license=('spdx:GPL-2.0-or-later')
depends=("${MINGW_PACKAGE_PREFIX}-openblas"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-*  ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"))
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc")
source=("https://github.com/wannier-developers/wannier90/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-build-on-mingw.patch")
sha256sums=('40651a9832eb93dec20a8360dd535262c261c34e13c41b6755fa6915c936b254'
            '02a279539eb4907ce1579c0f154103e791962d07e5c3ba373ee82706d50ca5e3')
noextract=("${_realname}-${pkgver}.tar.gz")

prepare() {
  echo "Extracting ${_realname}-${pkgver}.tar.gz ..."
  tar -xzf ${_realname}-${pkgver}.tar.gz || true

  cd "${srcdir}"/${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-build-on-mingw.patch

  cp -f ./config/make.inc.gfort ./make.inc
  sed -i "s|LIBS = -llapack -lblas|LIBS = -lopenblas|g" ./make.inc
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    sed -i "s|F90 = gfortran|F90 = flang|g" ./make.inc
  fi
}

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

  make all EXE_EXT=.exe
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  make install DESTDIR="${pkgdir}" PREFIX="${MINGW_PREFIX}" EXE_EXT=.exe

  mkdir -p "${pkgdir}"${MINGW_PREFIX}/include
  find . -type f -name '*.mod' -exec install {} "${pkgdir}"${MINGW_PREFIX}/include \;

  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
