# Maintainer: David Grayson <davidegrayson@gmail.com>

_realname=usbview
pkgbase=mingw-w64-${_realname}-git
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}-git"
provides=("${MINGW_PACKAGE_PREFIX}-${_realname}")
conflicts=("${MINGW_PACKAGE_PREFIX}-${_realname}")
replaces=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=671.7b0c7e24
pkgrel=1
pkgdesc='GUI for browsing all USB controllers and connected USB devices on your computer (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64')
url=''
license=('custom')
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  'patch'
  'git'
)
options=('strip')
_commit="7b0c7e24905cf4cafd33da5737b573696beb66b7"
source=("wds::git+https://github.com/Microsoft/Windows-driver-samples#commit=${_commit}"
        'my_xmlhelper.c'
        '01-uvcview-includes.patch'
        '03-resource-fix.patch'
        '04-redefinition.patch'
        '05-connection-statuses.patch'
        )
sha256sums=('SKIP'
            'c753691eea14e4cd267cc9a8e1afbf97648e9fda57cf68011384e4a5b1421c2e'
            'ea421bc7e5d56370d439850a766e8f5b439d9ecbef2e3b4c383abe2bb0cce01c'
            '2be3167e95f8d5d8abf91e43a49fac4593b8264df5c20478f476bdbe1bae89a3'
            '017bcb16508f6496e227dce96bd547ed1be20f2712742a05bafd4460924d3aad'
            'edcbf4392677934b21234e57a0094ce46f34053b51509719b186a18d7bdddc8e')

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

prepare() {
  cd "${srcdir}/wds/usb/usbview"

  # strsafe.h must be after tchar.h in mingw-w64.
  # winioctl.h must be before initguid.h
  # sal.h and usbspec.h are  needed.
  patch -p3 -i "${srcdir}/01-uvcview-includes.patch"

  # We exclude the XML stuff because it requires Visual C++ (.NET).
  rm usbschema.hpp xmlhelper.cpp
  cp "${srcdir}/my_xmlhelper.c" .

  # Fix some syntax errors that windres complains about
  patch -p1 -i "${srcdir}/03-resource-fix.patch"

  # Fix warnings about macro redefinitions.
  patch -p1 -i "${srcdir}/04-redefinition.patch"

  # Fix bad definition of array without a length.
  patch -p1 -i "${srcdir}/05-connection-statuses.patch"
}

build() {
  cd "${srcdir}"
  mkdir -p "build-${MINGW_CHOST}/include"
  cd "build-${MINGW_CHOST}"

  # Make sure mingw-w64's usb.h takes precedence over libusb-compat's.
  cp ${MINGW_PREFIX}/include/usb.h include

  windres ../wds/usb/usbview/uvcview.rc rc.so

  CFLAGS+=" -fcommon"
  gcc -mwindows --std=c99 ${CFLAGS} ${LDFLAGS} \
    -Iinclude \
    -DNTDDI_VERSION=0x06020000 -D_WIN32_WINNT=0x0602 \
    -DSTRSAFE_NO_DEPRECATE \
    ../wds/usb/usbview/*.c rc.so \
    -lcomctl32 -lcomdlg32 -lsetupapi -lshell32 -lshlwapi -lole32 -lgdi32 \
    -o usbview.exe
}

package() {
  cd "${srcdir}/wds"
  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
  cd "${srcdir}/build-${MINGW_CHOST}"
  mkdir "${pkgdir}${MINGW_PREFIX}/bin"
  install -Dm755 usbview.exe "${pkgdir}${MINGW_PREFIX}/bin"
}
