# Maintainer: David Grayson <davidegrayson@gmail.com>
#
# You might need to run your shell as administrator for devcon to work.

_realname=devcon
pkgbase=mingw-w64-${_realname}-git
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}-git"
provides=("${MINGW_PACKAGE_PREFIX}-${_realname}")
conflicts=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=r540.f0adcda0
pkgrel=3
_commit='f0adcda012820b1cd44a8b3a1953baf478029738'
pkgdesc='Search for and manipulate devices (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/Microsoft/Windows-driver-samples/tree/master/setup/devcon'
license=('custom')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "git"
             $([[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]] || echo "binutils"))
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
source=("wds::git+https://github.com/Microsoft/Windows-driver-samples#commit=${_commit}"
        "02-driverspecs.patch")
sha256sums=('SKIP'
            'b67d69e0623c79e10346afe357178618a8341a2cff3ce1ada0ed284280760856')

pkgver() {
  cd "${srcdir}"/wds
  printf "r%s.%s" "$(git rev-list --count "${_commit}")" "$(git rev-parse --short "${_commit}")"
}

prepare() {
  cd "${srcdir}/wds/setup/devcon"

  # dos2unix -q *.cpp *.h *.rc

  # Include driverspecs.h to get __drv_allocatesMem and similar.
  patch -p1 -i "${srcdir}/02-driverspecs.patch"

  # SetupScanFileQueue expects its callback to be stdcall.
  # patch -p1 -i "${srcdir}/03-stdcall-callback.patch"

  # We don't want MinGW to expand wildcards; we need to be able to
  # run commands like "devcon hwids *" to search for all devices.
  echo "int _dowildcard = 0;" > wildcard.cpp

  windmc msg.mc
}

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

  windres ../wds/setup/devcon/devcon.rc rc.so

  c++ -municode -Wno-write-strings ${CFLAGS} ${LDFLAGS} \
    -DWIN32_LEAN_AND_MEAN=1 -DUNICODE -D_UNICODE \
    ../wds/setup/devcon/*.cpp rc.so \
    -lsetupapi -lole32 \
    -o devcon.exe
}

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

  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin"
  install -Dm755 devcon.exe "${pkgdir}${MINGW_PREFIX}/bin"

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