# 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=42.c4ba9c6
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' 'clang64')
url=''
license=('custom')
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-gcc"
  'patch'
)
options=('strip')
source=("wds::git+https://github.com/Microsoft/Windows-driver-samples"
        'my_xmlhelper.c'
        '01-uvcview-includes.patch'
        '03-resource-fix.patch'
        '04-redefinition.patch'
        '05-connection-statuses.patch'
        )
sha256sums=('SKIP'
            'c753691eea14e4cd267cc9a8e1afbf97648e9fda57cf68011384e4a5b1421c2e'
            '36173cc353ca4901c23f971980a1ff59c007b952dd602d4faa5a34c7d7fc3518'
            '2be3167e95f8d5d8abf91e43a49fac4593b8264df5c20478f476bdbe1bae89a3'
            '017bcb16508f6496e227dce96bd547ed1be20f2712742a05bafd4460924d3aad'
            'edcbf4392677934b21234e57a0094ce46f34053b51509719b186a18d7bdddc8e')

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

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

  # strsafe.h must be after tchar.h in mingw-w64.
  # sal.h and usbspec.h are  needed.
  patch -p1 -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}/${MINGW_CHOST}/include/usb.h include

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

  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"
}
