#!/usr/bin/env sh

# usage: genshin-impact [-l | -m] [--] [client option flags]
# install and/or launch Genshin Impact under Wine 5.3 or later
# use '-l' flag to open the official launcher (for updates, etc.)
# WARNING: requires over 170GiB of available free space in ~/.local/opt

INSTALL_DIR="$HOME/.local/opt/genshin-impact"
LAUNCHER='drive_c/Program Files/Genshin Impact/launcher.exe'
GAME_FILES="${LAUNCHER%/*}/Genshin Impact Game"
EXEC='GenshinImpact.exe'
DPY_RES="$(xrandr -q | grep '[^dis]connected' \
	| egrep -o '([0-9]+x?)+' | fgrep 'x' | head -n 1)"

# external downloads
WINETRICKS='https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks'
INSTALLER='https://ys-api-os.mihoyo.com/event/download_porter/link/ys_global/genshinimpactpc/default'

# require wine-stable from wine-hq repos
# require at least wine 5.3
export PATH="/opt/wine-stable/bin:$PATH"
export WINE='wine64'
export WINEPREFIX="$INSTALL_DIR"
WINE_VER='5.3'

# first-run, download required files interactively
if [ ! -f "$INSTALL_DIR/$GAME_FILES/$EXEC" ]; then
	user-confirm 'Install Genshin Impact? (170GB free space required)' || exit 1
	$WINE --version > /dev/null || { echo "Install wine-stable."; exit 1; }
	$WINE --version | tr '-' '\t' | cut -f2 | while read -r ver; do
		[ $(echo "${ver%.*} >= $WINE_VER" | bc) -eq 1 ] && break
		echo "Wine version too old, install $WINE_VER or later."
		kill -- $$
	done

	# download additional components if required
	[ -d "$INSTALL_DIR" ] || $WINE wineboot -u

	for f in "$WINETRICKS" "$INSTALLER"; do
		if [ ! -f "$INSTALL_DIR/${f##*/}" ]; then
			wget -P "$INSTALL_DIR" "$f" || exit 1
		fi
	done

	# winetricks
	# DXVK latest (to fix issues with in-game web browser)
	# in-game browser fonts
	# mouse sensitivity issues
	for f in dxvk corefonts 'usetakefocus=n' 'mwo=disable'; do
		sh "$INSTALL_DIR/${WINETRICKS##*/}" "$f"
	done

	if [ ! -f "$INSTALL_DIR/$LAUNCHER" ]; then
		# follow prompts and install game when prompted, do not launch the game
		x-user-confirm -d 'Install the official launcher when prompted.
IMPORTANT: Exit without running the launcher.'
		sleep 2
		$WINE "$INSTALL_DIR/${INSTALLER##*/}"
	fi

	x-user-confirm -d 'Download and install the official game files to the default location when prompted.
IMPORTANT: Exit without launching the game.'
	sleep 2
	$WINE "$INSTALL_DIR/$LAUNCHER"
fi

# prevent DXVK from dumping cached shaders in $HOME
cd "$INSTALL_DIR/$GAME_FILES"

for f in "$@"; do
	case "$f" in
		-m) shift; WINE="mangohud $WINE";;
		-l) shift; $WINE "$INSTALL_DIR/$LAUNCHER"; exit;;
		--) shift; break;;
	esac
done

$WINE explorer /desktop="${0##*/},$DPY_RES" "$INSTALL_DIR/$GAME_FILES/$EXEC" "$@"