#!/usr/bin/bash
# pkhex for linux and macosx
# require wine or wine-stable or winehq-stable 9.0 or + and winetricks 20240105 or +
#sudo rm -rf "$HOME/.local/share/pkhex/"
XDG_DATA_HOME="$HOME/.local/share"
PKHEX_DATA_DIRECTORY="$HOME/.local/share/pkhex"
export WINEDEBUG="${WINEDEBUG--all}"
export WINEPREFIX="$HOME/.local/share/pkhex/wineprefixes/pkhex"
#this require for net 7 and net 8 or error
export DOTNET_ROOT="C:\Program Files\dotnet"
#this require for net 7 and net 8 or error
export DOTNET_BUNDLE_EXTRACT_BASE_DIR="C:\dotnet_bundle_extract"

if [ ! -d "$PKHEX_DATA_DIRECTORY" ]; then
  echo 'Installing PKHeX...'
  mkdir -p "${PKHEX_DATA_DIRECTORY}/bak"
  cd ${PKHEX_DATA_DIRECTORY}
  wget "https://github.com/amidevous/PKHeX/raw/master/linux-stable-version" -qO linux-stable-version
  source linux-stable-version
  rm -f PKHeX.exe $filename linux-stable-version
  wget https://github.com/amidevous/PKHeX/releases/download/24.01.12/$filename -qO $filename
  unzip $filename
  rm -f $filename
  mkdir -p $WINEPREFIX
  $winetrickinstall
  rm -f cfg.json
  wine PKHeX.exe
  echo 'Completed installing PKHeX.'
  exit
fi

case "$1" in
  'kill')
    wineserver -k "$2"
    ;;
  'winetricks')
    shift 1
    winetricks "$@"
    ;;
  'wine')
    shift 1
    wine "$@"
    ;;
  '-h'|'--help'|'help')
    echo 'Usage:'
    printf '%s [command]\t\t\tRun PKHeX (with optional command)\n' "$(basename "$0")"
    printf '%s kill [n]\t\t\tKill PKHeX (optinally with signal n)\n' "$(basename "$0")"
    printf '%s wine [command]\t\tExecute Wine command on the Wine prefix (winecfg, regedit, ...)\n' "$(basename "$0")"
    printf '%s winetricks [command]\t\tExecute Winetricks command on the Wine prefix\n' "$(basename "$0")"
    printf '%s {-h --help help}\t\tDisplay this help\n' "$(basename "$0")"
    ;;
  'update')
    echo 'Updating'
    cd ${PKHEX_DATA_DIRECTORY}
    wget "https://github.com/amidevous/PKHeX/raw/master/linux-stable-version" -qO linux-stable-version
    source linux-stable-version
    rm -f  linux-stable-version
    rm -f PKHeX.exe $filename
    wget https://github.com/amidevous/PKHeX/releases/download/24.01.12/$filename -qO $filename
    unzip $filename
    rm -f $filename
    $winetrickinstall
    ;;
  *)
    cd ${PKHEX_DATA_DIRECTORY}
    rm -f cfg.json
    wget "https://github.com/amidevous/PKHeX/raw/master/linux-stable-version" -qO linux-stable-version
    source linux-stable-version
    rm -f  linux-stable-version
    if [[ $require == $actual ]]
        then
        wine PKHeX.exe "$@"
    else
        rm -f PKHeX.exe $filename
        wget https://github.com/amidevous/PKHeX/releases/download/24.01.12/$filename -qO $filename
        unzip $filename
        rm -f $filename
        $winetrickinstall
        wine PKHeX.exe "$@"
    fi
    wineserver -w
    ;;
esac
