#!/bin/sh
set -o errexit

PLAYIT_LIB_PATHS="
$PWD
$(dirname "$0")/lib
${XDG_DATA_HOME:="${HOME}/.local/share"}/play.it
/usr/local/share/games/play.it
/usr/local/share/play.it
/usr/share/games/play.it
/usr/share/play.it"

if [ -z "$PLAYIT_LIB2" ]; then
	for playit_lib_path in $PLAYIT_LIB_PATHS; do
		if [ -e "${playit_lib_path}/libplayit2.sh" ]; then
			PLAYIT_LIB2="${playit_lib_path}/libplayit2.sh"
			break
		fi
	done
fi
if [ -z "$PLAYIT_LIB2" ]; then
	printf '\n\033[1;31mError:\033[0m\n'
	printf 'libplayit2.sh not found.\n'
	exit 1
fi
# shellcheck source=lib/libplayit2.sh
. "$PLAYIT_LIB2"
export PLAYIT_LIB2

# Exit if the current process has been spawned by the root user
init_fail_as_root

# Set the default and current options
init_options "$@"

# Display the help message, if called with no argument
if [ $# -eq 0 ]; then
	help
	exit 0
fi

# If some early action is set, run it then exit
init_early_actions

# Exit with an error if no archive is provided
if [ -z "${SOURCE_ARCHIVE_PATH:-}" ]; then
	error_archive_missing_from_arguments
	exit 1
fi

# Set the path to the working directory,
# so it can be used to cash the result of MD5 hashsums computations
init_working_directory

# Locate a game script by file name (and MD5 hash in case of names collision)
FILE_NAME=$(archive_name 'SOURCE_ARCHIVE')
GAME_SCRIPT=$(games_find_script_for_archive "$FILE_NAME")

# Load the game script
## PLAYIT_WORKDIR is passed to the new process to keep the cached computed MD5 hashes.
exec \
	env PLAYIT_WORKDIR="$PLAYIT_WORKDIR" \
	"$GAME_SCRIPT" "$@"
