# Maintainer: Pekka Helenius (~Fincer) <fincer89 at hotmail dot com>

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

pkgname=dxvk-nvapi-git
_pkgname=dxvk-nvapi
pkgver=580.6268
pkgrel=1
pkgdesc="Alternative NVAPI implementation on top of DXVK."
url="https://github.com/jp7677/dxvk-nvapi"
license=('MIT')

arch=('x86_64')
conflicts=(
  'dxvk-nvapi'
)
depends=('dxvk' 'wine' 'vulkan-icd-loader' 'lib32-vulkan-icd-loader')
makedepends=(
  'ninja'
  'meson>=0.49'
  'glslang'
  'mingw-w64-gcc'
  'git'
  'wine'
  'python'
)

_dxvknvapi_gitsrc=
_git_branch_dxvknvapi=master
_dxvknvapi_commit=HEAD

provides=('dxvk-nvapi')
options=(!strip !buildflags staticlibs)
source=(
  ${pkgname}::"${_dxvknvapi_gitsrc}#commit=${_dxvknvapi_commit}"
  'setup_dxvk_nvapi.sh'
)
sha256sums=(
  'SKIP'
  'e2ff99af4ecb739629e0f873077f986cffcc9418c8ecb7e6040744f05110afbb'
)

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

# Copy custom patches to correct location
if [[ $(find "${startdir}/dxvk-nvapi-patches" -mindepth 1 -maxdepth 1 -regex ".*\.\(patch\|diff\)$") ]]; then
    cp -r "${startdir}/dxvk-nvapi-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-nvapi-git"
  git checkout ${_git_branch_dxvknvapi}
  git reset --hard ${_dxvknvapi_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 NVAPI version tag
pkgver() {
  cd "${pkgname}"
  printf '%s.%s' $(git rev-list --count HEAD) $(git rev-parse --short HEAD | sed 's/\-[a-z].*//; s/\-/\./g; s/[a-z]//g')
}

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

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

  cp "${srcdir}"/setup_dxvk_nvapi.sh "${pkgdir}/usr/share/dxvk_nvapi/"

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

  chmod +x "${pkgdir}/usr/share/dxvk_nvapi/setup_dxvk_nvapi.sh"
  chmod +x "${pkgdir}/usr/bin/setup_dxvk_nvapi"
}