# Maintainer: Alexey Kasatkin <alexeikasatkin@gmail.com>
# ArchLinux maintainer: Jaroslav Lichtblau <dragonlord@aur.archlinux.org>
# Contributor: Brian Galey <bkgaley at gmail dot com>
# Contributor: Pietro Zambelli <peter.zamb at gmail dot com>

_realname=libspatialite
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=5.1.0
pkgrel=5
pkgdesc="SQLite extension to support spatial data types and operations (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://www.gaia-gis.it/fossil/libspatialite/index"
license=('spdx:MPL-1.1 OR LGPL-2.1-or-later OR GPL-2.0-or-later')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-autotools")
depends=("${MINGW_PACKAGE_PREFIX}-geos"
         "${MINGW_PACKAGE_PREFIX}-librttopo"
         "${MINGW_PACKAGE_PREFIX}-libfreexl"
         "${MINGW_PACKAGE_PREFIX}-libxml2"
         "${MINGW_PACKAGE_PREFIX}-minizip"
         "${MINGW_PACKAGE_PREFIX}-proj"
         "${MINGW_PACKAGE_PREFIX}-sqlite3"
         "${MINGW_PACKAGE_PREFIX}-libiconv")
source=("https://www.gaia-gis.it/gaia-sins//libspatialite-sources/${_realname}-${pkgver}.tar.gz"
        "01-fix-pkgconfig.patch"
        "0003-headers-gaiaconfig-remove-triplet.patch")
sha256sums=('43be2dd349daffe016dd1400c5d11285828c22fea35ca5109f21f3ed50605080'
            '165b82aaa8e81876dd6ca5b3adb32cc64a7f801c80ce797253f858c6bb9a6d93'
            '6846af0fa68d87b34c632a19c2194f2e8ac24d4260171845cb712ce9771cc620')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  sed -i configure.ac -e "s|mingw32|${MINGW_CHOST}|g"
  patch -p1 -i "${srcdir}/01-fix-pkgconfig.patch"
  patch -p1 -i "${srcdir}/0003-headers-gaiaconfig-remove-triplet.patch"

  # autoreconf to get libtool files with clang support
  autoreconf -fiv
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  ../${_realname}-${pkgver}/configure \
    --target=${MINGW_CHOST} \
    --build=${MINGW_CHOST} \
    --prefix=${MINGW_PREFIX} \
    --enable-rttopo \
    --enable-libxml2

  make
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  make DESTDIR="${pkgdir}" install
  # Fix mod_spatialite location to be possible: SELECT load_extension('mod_spatialite');
  mv "${pkgdir}${MINGW_PREFIX}/lib/mod_spatialite.dll" "${pkgdir}${MINGW_PREFIX}/bin/"

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done
}
