#!/bin/sh
# mood-launch <id> — one entry point for the dock, launcher and apps.
# Mood app id → mood-app; otherwise a .desktop id (apt / Flatpak / AppImage) → GIO (mood-open-desktop); otherwise a command.
# Every app runs in its own systemd scope (app-mood-<id>-<n>.scope) so Force stop (mood-kill) can find
# and kill all of its processes, even ones that outlive the window. systemd-run --scope execs in place,
# so the PID is unchanged: MOOD_SCOPED=$$ marks "already scoped" without leaking into apps it launches.
if [ "$MOOD_SCOPED" != "$$" ] && [ -n "$1" ] && command -v systemd-run >/dev/null 2>&1 \
   && systemctl --user show-environment >/dev/null 2>&1; then
  sid=$(printf '%s' "$1" | tr -c 'A-Za-z0-9_.' '_' | cut -c1-80)
  export MOOD_SCOPED=$$; exec systemd-run --user --scope --quiet --collect --slice=app.slice \
    --unit="app-mood-$sid-$$" --description="Mood app $1" -- "$0" "$@"
fi
unset MOOD_SCOPED
id="$1"; [ -n "$id" ] && shift
case "$id" in
  browser)  exec mood-browser "$@" ;;
  terminal) exec kitty ;;
  zapos)    exec /usr/lib/mood/runtime/zapos-classic ;;
esac
if [ -f "/usr/lib/mood/apps/$id/manifest.json" ]; then exec /usr/lib/mood/runtime/mood-app "$id" "$@"; fi
IFS=:
for d in $HOME/.local/share/flatpak/exports/share /var/lib/flatpak/exports/share $HOME/.local/share ${XDG_DATA_DIRS:-/usr/local/share:/usr/share}; do
  if [ -f "$d/applications/$id.desktop" ]; then unset IFS; exec /usr/lib/mood/runtime/mood-open-desktop "$d/applications/$id.desktop" "$@"; fi
done
unset IFS
if command -v flatpak >/dev/null 2>&1 && flatpak info "$id" >/dev/null 2>&1; then exec flatpak run "$id" "$@"; fi
command -v "$id" >/dev/null 2>&1 && exec "$id" "$@"
notify-send -a "Moodtop" "Can't open $id" "This app isn't installed. Find it in Mood Store."
exit 1
