#!/bin/bash
SELF=$(readlink -f "$0")
HERE="${SELF%/*}"
export PATH="${HERE}/usr/bin:${PATH}"
APP="${HERE}/usr/bin/adaptorex"

# yao-pkg binaries cause SIGBUS when executed directly from a read-only
# FUSE mount (like an AppImage). Copy the binary to /tmp and run from there.
RUNDIR="/tmp/adaptorex-run-$$"
mkdir -p "$RUNDIR"
cp "$APP" "$RUNDIR/adaptorex"
chmod +x "$RUNDIR/adaptorex"
APP="$RUNDIR/adaptorex"

# Clean up the temp copy when the app exits
cleanup() { rm -rf "$RUNDIR"; }
trap cleanup EXIT

# If already running inside a terminal, run directly
if [ -t 1 ]; then
  exec "$APP" "$@"
fi

RUN_AND_WAIT="\"$APP\"; EXIT=\$?; rm -rf \"$RUNDIR\"; echo; echo \"--- adaptorex has exited with code \$EXIT ---\"; read -rp \"Press Enter to close...\" _"

for TERM in \
  xterm \
  gnome-terminal \
  x-terminal-emulator \
  xfce4-terminal \
  konsole \
  mate-terminal \
  lxterminal \
  tilix \
  alacritty \
  kitty
do
  if command -v "$TERM" > /dev/null 2>&1; then
    case "$TERM" in
      gnome-terminal)
        exec "$TERM" -- bash -c "$RUN_AND_WAIT" -- "$@" ;;
      alacritty|kitty)
        exec "$TERM" -e bash -c "$RUN_AND_WAIT" -- "$@" ;;
      *)
        exec "$TERM" -e "bash -c '$RUN_AND_WAIT'" ;;
    esac
  fi
done

echo "No terminal emulator found. Install xterm and try again." >&2
exec "$APP" "$@"