# Maintainer: Fabien Chouteau <chouteau@adacore.com>

_realname=stlink
pkgbase="mingw-w64-${_realname}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.8.0
pkgrel=1
pkgdesc='Firmware programmer for STM32 STLINK v1/v2 protocol'
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/stlink-org/stlink'
license=(BSD)
depends=("${MINGW_PACKAGE_PREFIX}-libusb")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/stlink-org/stlink/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "0001-cmake-find-libusb.patch"
        "0002-cmake-remove-broken-things.patch"
        "0003-chip-config-relocate.patch")
sha256sums=('cff760b5c212c2cc480f705b9ca7f3828d6b9c267950c6a547002cd0a1f5f6ac'
            '836809f14729f3b272a182b881eae92a5c3e49056f43fb20462da5e1ab9c1580'
            '9b20ad3109253d1864cea41b1cff07b4aeeb9630a19a2309c728db8aef549d81'
            'c9b74edc132db86eadc327d8b5e44115800339a207720c1244aa1cdbe0ec996e')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/0001-cmake-find-libusb.patch"
  patch -p1 -i "${srcdir}/0002-cmake-remove-broken-things.patch"
  patch -p1 -i "${srcdir}/0003-chip-config-relocate.patch"
}

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

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${_extra_config[@]} \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

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

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .
}
