#!/usr/bin/env sh

set -eu

app_home=@PTLINUX_APP_ROOT@
install_directory=@PTLINUX_INSTALL_DIR@
python_bin="${PTLINUX_PYTHON:-python3}"

export PTLINUX_INSTALL_DIR="${install_directory}"
export PTLINUX_APP_HOME="${app_home}"

release_root=""
for candidate in "${app_home}/current" "${app_home}/previous" "${app_home}"
do
	# Installed releases already pass an isolated import self-check before their
	# activation link is changed. Keep only a cheap corruption/fallback check on
	# every boot instead of starting Python twice and importing the full CLI twice.
	if [ ! -r "${candidate}/ptlinux/__init__.py" ] || \
		[ ! -r "${candidate}/ptlinux/__main__.py" ] || \
		[ ! -r "${candidate}/ptlinux/cli.py" ] || \
		[ ! -r "${candidate}/ptdiag/__init__.py" ] || \
		[ ! -r "${candidate}/ptdiag/assbin.py" ] || \
		[ ! -r "${candidate}/ptdiag/logs.py" ]
	then
		continue
	fi
	release_root="${candidate}"
	break
done

if [ -z "${release_root}" ]
then
	printf '%s\n' "PristonTale EU Linux application files are missing or invalid: ${app_home}" >&2
	exit 1
fi

# Never let an unpacked older installer in the caller's current directory
# shadow the selected installed release. Children started by the dashboard
# inherit the same safe-path policy, package root, and no-bytecode policy.
export PYTHONSAFEPATH=1
export PYTHONDONTWRITEBYTECODE=1
export PYTHONPATH="${release_root}"

exec "$python_bin" -B -P -m ptlinux "$@"
