#!/usr/bin/env nix-shell
#!nix-shell -i bash -p sane-open-desktop -p xdg-utils

# use:
# rofi-run-command <handler>.desktop [cmd [args ...]]
# if a non-empty desktop file is provided, we'll just launch that.
# else, if the cmd is `xdg-open`, then we'll treat `args` as a URI and forward that to xdg-open.
# nothing else is as-yet supported.

desktop="$1"
shift
binary="$1"
shift
binArgs=("$@")

if [ "$desktop" != .desktop ]; then
  # launching an app; the file browser position is no longer interesting: clear it so it opens in ~ next time.
  # better UX would be to manage this in the other branch:
  # - open in ~ by default, regardless of last directory
  # - after launching a *file*, when that file is closed, re-open rofi in that file's directory.
  # however, `xdg-open` and the `OpenFile` xdg-desktop-portal API don't give any obvious way to block for the app to close.
  rm -f ~/.cache/rofi/rofi3.filebrowsercache
  exec sane-open-desktop "$desktop"
elif [ "$binary" = "xdg-open" ]; then
  exec xdg-open "$@"
fi

printf "no .desktop file, and unexpected binary; not invoking: %s %s" "$binary" "${binArgs[*]}" > /dev/null
exit 1
