_realname=qemu
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
_base_ver=6.0.0
_rc=
pkgver=${_base_ver}${_rc//-/.}
pkgrel=4
pkgdesc="QEMU - a generic and open source machine emulator and virtualizer (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
license=('GPL2' 'LGPL2')
url="https://qemu.org/"
options=('!emptydirs')
# optional features which introduce many dependencies should be added to makedepends
# for activation and optdepends for information
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-python"
  "${MINGW_PACKAGE_PREFIX}-python-sphinx"
  "${MINGW_PACKAGE_PREFIX}-spice"
  'perl' 'bison' 'bsdtar')
depends=(
  "${MINGW_PACKAGE_PREFIX}-capstone"
  "${MINGW_PACKAGE_PREFIX}-curl"
  "${MINGW_PACKAGE_PREFIX}-cyrus-sasl"
  "${MINGW_PACKAGE_PREFIX}-glib2"
  "${MINGW_PACKAGE_PREFIX}-gnutls"
  "${MINGW_PACKAGE_PREFIX}-gtk3"
  "${MINGW_PACKAGE_PREFIX}-libjpeg"
  "${MINGW_PACKAGE_PREFIX}-libnfs"
  "${MINGW_PACKAGE_PREFIX}-libpng"
  "${MINGW_PACKAGE_PREFIX}-libslirp"
  "${MINGW_PACKAGE_PREFIX}-libssh"
  "${MINGW_PACKAGE_PREFIX}-libssp"
  "${MINGW_PACKAGE_PREFIX}-libtasn1"
  "${MINGW_PACKAGE_PREFIX}-libusb"
  "${MINGW_PACKAGE_PREFIX}-libxml2"
  "${MINGW_PACKAGE_PREFIX}-lzo2"
  "${MINGW_PACKAGE_PREFIX}-nettle"
  "${MINGW_PACKAGE_PREFIX}-pixman"
  "${MINGW_PACKAGE_PREFIX}-SDL2"
  "${MINGW_PACKAGE_PREFIX}-SDL2_image"
  "${MINGW_PACKAGE_PREFIX}-snappy"
  "${MINGW_PACKAGE_PREFIX}-usbredir"
  "${MINGW_PACKAGE_PREFIX}-zstd"
)
optdepends=(
  "${MINGW_PACKAGE_PREFIX}-spice: to enable spice usage"
)
source=("https://download.qemu.org/${_realname}-${pkgver}.tar.xz"{,.sig}
  "https://gitlab.com/qemu-project/qemu/-/commit/1c96386.patch"
  msys2.readme.txt
  msys2.examples.tests.sh)
sha256sums=('87bc1a471ca24b97e7005711066007d443423d19aacda3d442558ae032fa30b9'
            'SKIP'
            'fbc926b29350d53278b2481c6513f8f02f4efa5851e44b75dcaca65cdcf423b8'
            '7d699824c1c89da7b2ef898c0eb99a4d9daeb5bfa72e516bebe188a127b46f39'
            '0b6f2321ce2bf8fcc2ebe22a37b27879d661273564a68c32a589ce5c49063872')
validpgpkeys=('CEACC9E15534EBABB82D3FA03353C9CEF108B584') # Michael Roth <flukshun@gmail.com>
# tar cannot create links, to keep build running, manual extraction is required
noextract=(${_realname}-${pkgver}.tar.xz)

prepare() {
  [[ -d "${srcdir}"/${_realname}-${pkgver} ]] && rm -rf "${srcdir}"/${_realname}-${pkgver}
  # tar cannot create links here, therefore hide the failure
  tar -xf ${srcdir}/${_realname}-${pkgver}.tar.xz -C ${srcdir} || true

  cd "${srcdir}/${_realname}-${pkgver}"
  patch -Np1 -i "${srcdir}/1c96386.patch"
}

build() {
  # Requirements as documented in https://wiki.qemu.org/Hosts/W32#Native_builds_with_MSYS2
  #   Execution of
  #     configure --cross-prefix=${CARCH}-w64-mingw32-
  #   and
  #   Providing cross-prefixed binaries by copying
  #     ${CARCH}-w64-mingw32-objcopy.exe using objcopy.exe
  #     ${CARCH}-w64-mingw32-windres.exe using windres.exe
  #     ${CARCH}-w64-mingw32-ranlib.exe  using ${CARCH}-w64-mingw32-gcc-ranlib.exe
  #     ${CARCH}-w64-mingw32-ar.exe      using ${CARCH}-w64-mingw32-gcc-ar.exe
  #     ${CARCH}-w64-mingw32-nm.exe      using nm.exe
  LDFLAGS+=" -fstack-protector"
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  mkdir -p "${srcdir}"/build-${CARCH} && cd "${srcdir}"/build-${CARCH}

  # We need to provide all expected cross-prefixed tools without links or copying!
  # We will also provide undocumented ${CARCH}-w64-mingw32-strip.exe using strip.exe
  # Msys2 already provides some duplicates in ${MINGW_PREFIX}/bin:
  #   gcc-ar.exe is ${CARCH}-w64-mingw32-gcc-ar.exe
  #   gcc-ranlib.exe is ${CARCH}-w64-mingw32-gcc-ranlib.exe
  # These common, not prefixed exports read by configure fulfill all qemu requirements
  export AR=gcc-ar
  export NM=nm
  export OBJCOPY=objcopy
  export RANLIB=gcc-ranlib
  export STRIP=strip
  export WINDRES=windres

  # configure failes to create links, which can be ignored
  # qemu enables all features if possible, so keep it simple
  # For faster testing:
  #TARGETLIST="--target-list=x86_64-softmmu"
  # configuration of paths for win32 - fixes in package():
  # intention: leave all core files in one directory - lib/qemu
  ../${_realname}-${pkgver}/configure $TARGETLIST \
    --cross-prefix=${CARCH}-w64-mingw32- \
    --python=${MINGW_PREFIX}/bin/python \
    --prefix=${MINGW_PREFIX} \
    --bindir=${MINGW_PREFIX}/lib/qemu \
    --datadir=${MINGW_PREFIX}/lib/qemu \
    --localedir=${MINGW_PREFIX}/share/locale \
    --mandir=${MINGW_PREFIX}/share/man \
    --docdir=${MINGW_PREFIX}/share/doc/qemu

  # Finally build
  make
}

check() {
  cd "${srcdir}"/build-${CARCH}
  # Tests are not performed in CI
  # For local testing: perform, but do not fail
  make test || true
}

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

  # Fix failure of make install introduced by Sphinx >=4.0.0
  # Sphinx >=4.0.0 puts man pages to docs/(1|7|8)/ and not to docs/ as expected
  # TODO Try to remove with next Qemu release
  find docs -type f -regextype grep -regex "docs/[0-9]/.*" -exec \
    cp -pv {} docs/ \;

  # Install to ${pkgdir}
  make DESTDIR="${pkgdir}" install

  # ${MINGW_PREFIX} was installed somewhere below ${pkgdir}, determine ...
  local P_INSTALL=$(find "${pkgdir}" -name "$(basename ${MINGW_PREFIX})" -type d)
  # Move directly to ${pkgdir}, if not already there
  [ -d "${pkgdir}"/${MINGW_PREFIX} ] || mv -v "$P_INSTALL" "${pkgdir}"/

  # To enable usage relative paths for next operations
  cd "${pkgdir}"/${MINGW_PREFIX}

  # Move to standard dirs in share/
  mkdir -pv share
  mv -v lib/qemu/applications share/
  mv -v lib/qemu/icons share/

  # Fix firmware descriptors
  # see https://bugzilla.redhat.com/show_bug.cgi?id=1728652#c7
  mkdir -pv share/qemu
  mv -v lib/qemu/firmware share/qemu/
  find share/qemu/firmware -type f -exec \
    sed -i "s%\(\"filename\"\s*:\s*\"\).*edk2%\1${MINGW_PREFIX}/lib/qemu/edk2%" {} \;

  # For executables in lib/qemu/ create wrappers in bin/
  mkdir -pv bin
  local LIBEXES=$(find lib/qemu -name "*.exe" ! -name "*w.exe")
  local LIBEXE=""
  for LIBEXE in $LIBEXES
  do
    local EXE=$(basename $LIBEXE)
    local WRAPPER=bin/$EXE
    echo "#!/bin/bash"                                     >> $WRAPPER
    echo "export PATH=\"${MINGW_PREFIX}/lib/qemu:\$PATH\"" >> $WRAPPER
    echo "exec ${MINGW_PREFIX}/lib/qemu/$EXE \"\$@\""      >> $WRAPPER
    chmod u+x $WRAPPER
  done

  # Add all licenses found in qemu sources to share/licences/qemu/
  mkdir -pv share/licenses/qemu
  tar -C "${srcdir}"/${_realname}-${pkgver} -c $(
    cd "${srcdir}"/${_realname}-${pkgver} &&
      find -iname "*COPYING*" -or -iname "*LICENSE*" |
      grep -v "\s" |
      egrep -v "meson.(test|msi|doc)" |
      egrep -v "(license.c|relicense.pl|license.doctree|LicenseCheck)"
    ) | tar -C share/licenses/qemu -xv

  # Add msys2 docs
  mkdir -pv share/doc/qemu
  cp -pv "${srcdir}"/msys2.readme.txt share/doc/qemu/
  cp -pv "${srcdir}"/msys2.examples.tests.sh share/doc/qemu/
}
