#!/bin/bash
# A script added on the Desktop page (UserApps), run from its own folder:
#   bannerlator-script-run /opt/droiddeck-apps/<id> [args...]
set -u
dir=${1:?usage: bannerlator-script-run <added app directory> [args...]}
shift
entry=$(cat "$dir/entry" 2>/dev/null) || { echo "bannerlator-script-run: $dir has no entry" >&2; exit 127; }
cd -P "$dir/files" 2>/dev/null || { echo "bannerlator-script-run: $dir/files is missing; add the script again" >&2; exit 127; }
folder=$PWD
# Shared storage is noexec, so the script is handed to its interpreter rather than executed.
first=
IFS= read -r first < "$entry"
first=${first%$'\r'}
interp=(/bin/bash)
case $first in '#!'*) read -r -a interp <<< "${first#'#!'}" ;; esac
echo "== script $entry in $folder (${interp[*]})"
case ${DBUS_SESSION_BUS_ADDRESS:-} in
  unix:*) "${interp[@]}" "./$entry" "$@" ;;
  *) unset DBUS_SESSION_BUS_ADDRESS
     if command -v dbus-run-session >/dev/null 2>&1; then
       dbus-run-session -- "${interp[@]}" "./$entry" "$@"
     else
       "${interp[@]}" "./$entry" "$@"
     fi ;;
esac
rc=$?
# A launcher script often starts the game and returns; the session lasts while it runs.
running() {
  local p exe
  for p in /proc/[0-9]*; do
    exe=$(readlink "$p/exe" 2>/dev/null) || continue
    case $exe in "$folder"/*) return 0 ;; esac
  done
  return 1
}
while running; do sleep 2; done
exit $rc
