# Maintainer: Pekka Helenius (~Fincer) <fincer89 at hotmail dot com>
# Contributor: AdriƠ Cereto i MassaguƩ <ssorgatem at gmail.com>

# Override /etc/makepkg.conf PKGDEST variable if it's enabled
PKGDEST="${PWD}"

pkgname=dxvk-git
_pkgname=dxvk
pkgver=1.2.1.4
pkgrel=1
pkgdesc="A Vulkan-based compatibility layer for Direct3D 9/10/11 which allows running 3D applications on Linux using Wine."
url="https://github.com/doitsujin/dxvk"
license=('custom:zlib/libpng')

arch=('x86_64')
conflicts=(
  'd9vk-bin'
  'd9vk-mingw'
  'd9vk-mingw-git'
  'd9vk-winelib'
  'd9vk-winelib-git'

  'dxvk-bin'
  'dxvk-winelib'
  'dxvk-winelib-git'
  'dxvk-legacy-git'
  'dxvk-mingw-git'
)
depends=('wine' 'vulkan-icd-loader' 'lib32-vulkan-icd-loader')
makedepends=(
  'ninja'
  'meson>=0.43'
  'glslang'
  'mingw-w64-gcc'
  'git'
  'wine'
)

_dxvk_gitsrc=
_git_branch_dxvk=master
_dxvk_commit=HEAD

provides=('dxvk')
options=(!strip !buildflags staticlibs)
source=(${pkgname}::"${_dxvk_gitsrc}#commit=${_dxvk_commit}")
sha256sums=('SKIP')

##############################

# Copy custom patches to correct location
if [[ $(find "${startdir}/dxvk-patches" -mindepth 1 -maxdepth 1 -regex ".*\.\(patch\|diff\)$") ]]; then
    cp -r "${startdir}/dxvk-patches/"*.{patch,diff} "${startdir}"/
    p=0
    for patch in $(find . -mindepth 1 -maxdepth 1 -regex ".*\.\(patch\|diff\)$"); do
        patches[$p]="$(basename ${patch})"
        let p++
    done
    unset p
    source+=(${source[@]} ${patches[@]})
fi

# Reset git tree and apply custom patches
prepare() {

  cd "${srcdir}/dxvk-git"
  git checkout ${_git_branch_dxvk}
  git reset --hard ${_dxvk_commit} # Restore tracked files
  git clean -d -x -f         # Delete untracked files
  git submodule update --init --recursive

  # Apply patches, if present
  if [[ $(ls "${srcdir}"/*.{patch,diff} 2>/dev/null | wc -w) -ne 0 ]]; then

  # Apply all custom patches
  msg2 "Applying custom patches..."

    for i in "${srcdir}"/*.{patch,diff}; do
      if [[ -f ${i} ]]; then
        patch -Np1 < ${i}
      fi
    done

  fi

}

##############################

# Retrieve DXVK version tag
pkgver() {
  cd "${pkgname}"
  printf '%s' $(git describe --long --always | sed 's/\-[a-z].*//; s/\-/\./g; s/[a-z]//g')
}

# Launch DXVK build script
build() {
  cd "${pkgname}"
  ./package-release.sh ${pkgver} "${srcdir}"/build --no-package
}

# Bundle the compiled files
package() {
  mkdir -p "${pkgdir}"/usr/{bin,share/dxvk}
  cp -r "${srcdir}"/build/${_pkgname}-${pkgver}/* "${pkgdir}/usr/share/dxvk/"

  echo -e "#!/bin/sh" > "${pkgdir}/usr/bin/setup_dxvk"
  echo -e "
cd /usr/share/dxvk/
./setup_dxvk.sh \${@}
" >> "${pkgdir}/usr/bin/setup_dxvk"

  chmod +x "${pkgdir}/usr/bin/setup_dxvk"
}