#!/usr/bin/env bash
set -euo pipefail

wine_root="${WINE_STAGING_921_ROOT:-${WINE921_ROOT:-$HOME/.local/opt/wine-staging-9.21}}"
wine_loader="${WINE_STAGING_921_LOADER:-wine64}"

if [[ ! -x "$wine_root/usr/bin/$wine_loader" || ! -x "$wine_root/usr/bin/wineserver" ]]; then
  cat >&2 <<EOF
Wine 9.21 was not found under:
  $wine_root

Install it by extracting the Arch Linux Archive package there, for example:
  mkdir -p "$wine_root"
  curl -L -o /tmp/wine-staging-9.21-1-x86_64.pkg.tar.zst \\
    "https://archive.archlinux.org/packages/w/wine-staging/wine-staging-9.21-1-x86_64.pkg.tar.zst"
  bsdtar -C "$wine_root" -xf /tmp/wine-staging-9.21-1-x86_64.pkg.tar.zst
EOF
  exit 127
fi

export PATH="$wine_root/usr/bin:$PATH"
if [[ -n "${WINEDLLPATH:-}" ]]; then
  export WINEDLLPATH="$wine_root/usr/lib:$WINEDLLPATH"
else
  export WINEDLLPATH="$wine_root/usr/lib"
fi
export WINESERVER="$wine_root/usr/bin/wineserver"

case "${1:-}" in
  wine|wine64|wineboot|winecfg|wineconsole|winedbg|winefile|winepath|wineserver|regedit|msiexec)
    command="$1"
    shift
    exec "$wine_root/usr/bin/$command" "$@"
    ;;
esac

exec "$wine_root/usr/bin/$wine_loader" "$@"
