#!/bin/sh
# metatana-cli-wrapper
# `metatana` command shipped inside the MetaTana desktop app (macOS:
# MetaTana.app/Contents/Resources/bin, Linux: <install>/resources/bin).
# It runs the bundled CLI with the app's own runtime, so no separate Node is
# needed. Settings and the Linux packages link this file into PATH.
set -e

self="$0"
while [ -L "$self" ]; do
  link="$(readlink "$self")"
  case "$link" in
    /*) self="$link" ;;
    *) self="$(dirname "$self")/$link" ;;
  esac
done
resources_dir="$(cd "$(dirname "$self")/.." && pwd -P)"

if [ -x "$resources_dir/../MacOS/MetaTana" ]; then
  app_binary="$resources_dir/../MacOS/MetaTana"
elif [ -x "$resources_dir/../MetaTana" ]; then
  app_binary="$resources_dir/../MetaTana"
elif [ -x "$resources_dir/../metatana" ]; then
  app_binary="$resources_dir/../metatana"
else
  echo "metatana: cannot find the MetaTana app next to $resources_dir" >&2
  exit 1
fi

unset ELECTRON_RUN_AS_NODE

# With no arguments, open the app as `metatana` always has on Linux.
if [ "$#" -eq 0 ]; then
  exec "$app_binary"
fi

# Electron refuses to start as root on Linux without --no-sandbox. The CLI
# never shows web content, so the Chromium sandbox has nothing to protect.
sandbox_flag=""
if [ "$(uname -s)" = "Linux" ] && [ "$(id -u)" = "0" ]; then
  sandbox_flag="--no-sandbox"
fi

# --log-level=3: Chromium's own error lines stay out of the command's stderr.

# Linux without a display (for example over SSH): start Electron without a
# display connection, and with no GPU process, whose failure to find a display
# prints 20 lines. The signed-in session usually cannot be read there (no
# keyring), so set METATANA_HOSTED_SESSION_TOKEN for Pro access in that case.
if [ "$(uname -s)" = "Linux" ] && [ -z "${DISPLAY:-}" ] && [ -z "${WAYLAND_DISPLAY:-}" ]; then
  exec "$app_binary" $sandbox_flag --log-level=3 --disable-gpu --ozone-platform=headless --metatana-cli -- "$@"
fi

exec "$app_binary" $sandbox_flag --log-level=3 --metatana-cli -- "$@"
