#!/bin/bash

set -euo pipefail

# verbose
# set -x

SCRIPT_DIR=$(dirname "$(realpath "$0")")
PV_DIR="$SCRIPT_DIR/pv-runtime"
RUNTIME="steam-runtime-steamrt"
RUNTIME_DIR="$PV_DIR/$RUNTIME"
SDK=0
VERBOSE="${STEAM_LINUX_RUNTIME_VERBOSE:-0}"

export SHELL=/bin/bash

function verbose()
{
	if [ "$VERBOSE" != "1" ]; then
		return
	fi

	echo "$@"
}

function info()
{
	echo "$@"
}

function error()
{
	echo "ERROR:" "$@" >&2
	exit 1
}

function print_usage()
{
	NAME=$0
	cat <<EOF
Usage: $NAME [--sdk] -- <command>

Examples:
    # Run a one shot command inside the standard runtime
    $NAME -- ./steam

    # Start a shell in a container
    $NAME -i steamrt-steamrt3c -- /bin/bash

Options:
    -h|--help            Print this help text
       --sdk             Use the SDK variant of the runtime
    -v|--verbose         Verbose output
EOF
}

while [[ $# -gt 0 ]]; do
	case $1 in
		-v| --verbose) VERBOSE=1; shift;;
			--sdk) SDK=1; shift;;
		-h| --help) print_usage; exit 0;;
		--) shift; break ;;
		*) print_usage; error "Unknown option $1";;
	esac
done


function unpack_runtime()
{
	if [ -x "$PV_DIR/steam-runtime-steamrt.sh" ]; then
		# Unpack $RUNTIME/ from $RUNTIME.tar.xz if necessary,
		# using $RUNTIME.version.txt to check whether it changed.
		# Outputs the path to _v2-entry-point on stdout, we ignore this
		"$PV_DIR/steam-runtime-steamrt.sh" \
			--unpack-dir="$PV_DIR" \
			--runtime="$RUNTIME" \
			>/dev/null
	fi
}

function pv_run()
{
	exec "$RUNTIME_DIR/run" --for-steam-client -- "$@"
}

unset DEBUGINFOD_URLS

if [ -n "${STEAM_RUNTIME_STEAMRT-}" ]; then
	verbose "Running command in custom runtime $STEAM_RUNTIME_STEAMRT:" "$@"
	RUNTIME_DIR="$STEAM_RUNTIME_STEAMRT"
	pv_run "$@"
elif [[ "$SDK" == "1" ]]; then
	SDK_ROOT="$(realpath "$SCRIPT_DIR/../../tools/runtime/linux-2/pv-sdk/steamrt3c")"

	# setup the base pressure-vessel environment
	verbose "Setting up base pressure vessel environment"
	unpack_runtime

	# Edit the run script so it can operate on foreign filesystems
	# NOTE(andresr): need to add an option for this in upstream pv
	verbose "Updating run to support filesystem overrides"
	if ! grep -q '^dir_orig=' "$RUNTIME_DIR/run"; then
		# shellcheck disable=SC2016
		sed -i '/^dir=/ {
			s/^dir=/dir_orig=/
			a dir="${PV_DIR_OVERRIDE:-$dir_orig}"
		}' "$RUNTIME_DIR/run"
	fi

	# Build the sdk filesystem if necessary
	verbose "Building SDK filesystem"
	ninja -C "$SDK_ROOT" --quiet

	# Run pressure-vessel with this new filesystem
	verbose "Running command in SDK runtime:" "$@"
	export PV_DIR_OVERRIDE="$SDK_ROOT/files"
	exec "$RUNTIME_DIR/run" --devel --for-steam-client -- "$@"
else
	verbose "Running command in standard runtime:" "$@"
	unpack_runtime
	pv_run "$@"
fi
