#!/bin/sh
# DooDooBlox (gametest1) for Linux.
#
# Downloads the native DooDooBlox launcher (DooDooBloxLauncher) and runs it. The launcher is the Windows
# DoodooPlayerLauncher.exe for Linux: the same window, logo, progress bar and texts; it installs and updates the
# native DooDooBlox player (the same content, CoreGui and loading screen as the Windows client) and makes the
# site's Play button open it.
#
#   sh DooDooBloxLinux.sh                install or update; then press Play on any game
#   sh DooDooBloxLinux.sh --uninstall    remove DooDooBlox
#
# Needs a 64-bit (x86_64) Linux with glibc 2.34 or newer (Ubuntu 22.04, Debian 12, Fedora 35 and later),
# OpenGL 2.1, and the SDL2 and curl libraries, which most desktops already have.
set -u

HOST="${DOODOO_HOST:-gametest1.doodooblox.wtf}"
BASE="${XDG_DATA_HOME:-$HOME/.local/share}/doodooblox-gametest1"
LAUNCHER="$BASE/DooDooBloxLauncher"

say() {
	printf '%s\n' "$1" >&2
	if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
		if command -v zenity >/dev/null 2>&1; then zenity --error --title="DoodooBlox" --no-wrap --text="$1" 2>/dev/null
		elif command -v kdialog >/dev/null 2>&1; then kdialog --title "DoodooBlox" --error "$1"
		elif command -v notify-send >/dev/null 2>&1; then notify-send "DoodooBlox" "$1"
		fi
	fi
}

fetch() { # url file
	if command -v curl >/dev/null 2>&1; then curl -fsSL --retry 2 --connect-timeout 20 -o "$2" "$1"
	elif command -v wget >/dev/null 2>&1; then wget -q -T 60 -O "$2" "$1"
	else return 1
	fi
}

if [ "$(id -u)" = 0 ]; then
	echo "Run DooDooBloxLinux.sh as your own user, not root." >&2
	exit 1
fi
if [ "$(uname -m)" != x86_64 ]; then
	say "DooDooBlox for Linux needs a 64-bit PC (x86_64); this one is $(uname -m)."
	exit 1
fi

mkdir -p "$BASE"
part="$LAUNCHER.part"
if fetch "https://$HOST/version-latest-DooDooBloxLauncher" "$part" && [ "$(head -c 4 "$part" | tail -c 3)" = ELF ]; then
	chmod +x "$part" && mv -f "$part" "$LAUNCHER"
else
	rm -f "$part"
fi
if [ ! -x "$LAUNCHER" ]; then
	say "Could not download DooDooBlox from $HOST. Check your connection and try again."
	exit 1
fi

# A library the launcher needs is missing: say which package brings it.
if ! check=$("$LAUNCHER" --help 2>&1 >/dev/null); then
	case "$check" in
	*libSDL2*) lib="SDL2"; apt="libsdl2-2.0-0"; dnf="SDL2"; pac="sdl2" ;;
	*) lib="a library"; apt="libsdl2-2.0-0 libcurl4"; dnf="SDL2 libcurl"; pac="sdl2 curl" ;;
	esac
	say "DooDooBlox needs $lib. Install it with:
    sudo apt install $apt      (Debian, Ubuntu, Mint)
    sudo dnf install $dnf      (Fedora)
    sudo pacman -S $pac        (Arch)

Details: $check"
	exit 1
fi

exec "$LAUNCHER" "$@"
