#!/usr/bin/env bash
# spell-checker: ignore sapi WINEARCH WINEPREFIX WINETRICKS
set -b

THIS_DIR="$(cd "$(dirname "$0")" && pwd)"
WINE_ROOT_DIR="$THIS_DIR/tai-wine"
TAI_AWAKENING_EXE_NAME='TAI Awakening.exe'
PROTON_VERSION='GE-Proton9-11'
PROTON_ARCHIVE_NAME="$PROTON_VERSION.tar.gz"
PROTON_URL="https://github.com/GloriousEggroll/proton-ge-custom/releases/download/$PROTON_VERSION/$PROTON_ARCHIVE_NAME"
WINETRICKS_URL='https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks'

export WINEARCH=win64
export WINE="$WINE_ROOT_DIR/GE-Proton9-11/files/bin/wine64"
export WINEPREFIX="$WINE_ROOT_DIR/prefix"
WINETRICKS="$WINE_ROOT_DIR/winetricks"

function fail() # errorMessage: str
{
    errorMessage="$1"
    echo -en "\x1b[31;1mError\x1b[0m: "
    echo "$errorMessage"
    exit 1
}

function note() # message: str
{
    message="$1"
    echo -en "\x1b[34;1mNote\x1b[0m: "
    echo "$message"
}

function downloadProton()
{
    command -v wget > /dev/null || fail 'wget not available or not installed'
    command -v tar > /dev/null || fail 'tar not available or not installed'

    note "Create directory '$WINE_ROOT_DIR'"
    mkdir -p "$WINE_ROOT_DIR"

    note "Downloading '$PROTON_VERSION'"
    wget -P "$WINE_ROOT_DIR" "$PROTON_URL"

    note "Unpacking '$PROTON_VERSION'"
    tar -xvf "$WINE_ROOT_DIR/$PROTON_ARCHIVE_NAME" -C "$WINE_ROOT_DIR"

    note "Downloading 'winetricks'"
    wget -P "$WINE_ROOT_DIR" "$WINETRICKS_URL"
    chmod +x "$WINETRICKS"
}

function initPrefix()
{
    note 'Initialising wine prefix'
    "$WINE" cmd /c 'echo Ready'

    note 'Configuring wine prefix'
    "$WINETRICKS" -q dotnet48 sapi ie8
}

note "Running from: '$THIS_DIR'"

[ -f "$THIS_DIR/$TAI_AWAKENING_EXE_NAME" ] || fail "'$TAI_AWAKENING_EXE_NAME' is not in this directory"

if [ ! -d "$WINE_ROOT_DIR" ]
then
    note "This is the first run which will acquire wine and tools into '$WINE_ROOT_DIR'"
    note "It will also create and initialise a wine prefix in '$WINEPREFIX'"
    note "Ignore the 'fixme' and 'err' messages that are shown during setup, that's normal for wine"
    note "Subsequent runs will just start '$TAI_AWAKENING_EXE_NAME'"
    read -rp 'Continue (y/n)?' choice
    [ "$choice" != 'y' ] && exit 1

    downloadProton
    initPrefix
fi

note "Using wine root dir at '$WINE_ROOT_DIR'"
note "Launching '$TAI_AWAKENING_EXE_NAME'"
cd "$THIS_DIR" && "$WINE" "$TAI_AWAKENING_EXE_NAME"
