#!/bin/sh
# The `termiyo` command, as a two-step: find a JavaScript runtime, then run
# termiyo.mjs with it.
#
# The runtime we prefer is the application's own: the app binary, started in its
# CLI mode (`--termiyo-cli`, src/main/cliMode.ts), which runs the same termiyo.mjs
# from inside the app and exits. So the command works on a machine with no node
# installed, which is most machines. It used to run this directory's termiyo.mjs
# with the binary as a plain Node (ELECTRON_RUN_AS_NODE); the packaged app has
# that fuse OFF since N22-04, because it let any program run under Termiyo's
# signed identity, and with it off the variable does nothing.
#
# This script is meant to be symlinked onto PATH, so it resolves its own
# symlinks before looking around: `dirname $0` from /usr/local/bin would find
# nothing. `readlink -f` is not portable enough to rely on (BSD and older macOS
# do not have it), hence the loop.
set -e

target=$0
while [ -L "$target" ]; do
  link=$(readlink "$target")
  case $link in
    /*) target=$link ;;
    *) target=$(dirname "$target")/$link ;;
  esac
done
dir=$(CDPATH= cd -- "$(dirname -- "$target")" && pwd)

# Where the app binary sits relative to this script, once it is installed:
#   macOS   Termiyo.app/Contents/Resources/cli/termiyo -> ../../MacOS/Termiyo
#   Linux   /opt/Termiyo/resources/cli/termiyo         -> ../../termiyo
#
# The switches are Chromium's and have to be on the command line, because
# Chromium reads them before any of the app's code runs (cliMode.ts has the
# measurements): no display is needed (headless), its logging stays off a
# script's stderr, and on Linux no sandbox — the CLI mode opens no web page,
# and the setuid helper aborts the whole process wherever it is not installed
# root-owned. `--` ends Chromium's switches, so a host name cannot become one.
switches="--ozone-platform=headless --log-level=3"
case $(uname -s) in Linux) switches="$switches --no-sandbox" ;; esac
for candidate in "$dir/../../MacOS/Termiyo" "$dir/../../termiyo" "$dir/../../Termiyo"; do
  if [ -x "$candidate" ]; then
    # shellcheck disable=SC2086 # the switches are meant to split
    exec "$candidate" --termiyo-cli $switches -- "$@"
  fi
done

# Not installed beside an app — a checkout, or the script copied somewhere. Any
# Node will do; the command has no dependencies.
if command -v node >/dev/null 2>&1; then
  exec node "$dir/termiyo.mjs" "$@"
fi

echo "termiyo: no Termiyo application beside this script and no node on PATH." >&2
exit 3
