#!/bin/bash
#
# Purpose : Run a CoreDesktop command in the terminal the extension opened, and
#           record whether it's running or how it ended, so the top bar menu
#           can show it and notify when it's done.
#
# run-tracked <name> <command> [arguments...]
#
# Writes $XDG_RUNTIME_DIR/coredesktop-extension/<name>.status: "running <pid>"
# while the command runs, then "exit <status>". Closing the window while the
# command runs records 129, like a shell would.

name="$1"
shift
dir="${XDG_RUNTIME_DIR:-/tmp}/coredesktop-extension"
mkdir -p -m 700 "$dir"
status_file="$dir/$name.status"

# The commands live in ~/.local/bin, which GNOME Shell's PATH may not include
export PATH="$HOME/.local/bin:$PATH"

write_status() {
  printf '%s\n' "$1" > "$status_file.tmp" && mv -f "$status_file.tmp" "$status_file"
}

finished=""
finish() {
  [ -n "$finished" ] && return
  finished=1
  write_status "exit $1"
}
trap 'finish 129; exit 129' HUP
trap 'finish 130; exit 130' TERM

write_status "running $$"
"$@"
code=$?
finish "$code"

# e.g. "configure core", without ~/.local/bin/
what="${1##*/}${2:+ ${*:2}}"

echo
if [ "$code" -eq 0 ]; then
  printf '\e[1;32m✔ %s finished.\e[0m\n' "$what"
else
  printf '\e[1;31m✘ %s ended with status %d.\e[0m\n' "$what" "$code"
fi
read -rp "Press Enter to close this window."
