#!/usr/bin/env bash
set -u

# LightDM can start Openbox before the user PipeWire/WirePlumber services have
# published a default sink or Tint2 has claimed the notification area. Keep a
# small supervisor alive. A new session deliberately replaces the previous
# supervisor: an old Openbox autostart process can survive logout with a stale
# X connection, and merely refusing the new process would leave no tray icon.
RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
mkdir -p "${RUNTIME_DIR}"
LOCK_FILE="${RUNTIME_DIR}/totaljs-pasystray.lock"
PID_FILE="${RUNTIME_DIR}/totaljs-pasystray.pid"
exec 9>"${LOCK_FILE}"

if ! flock -n 9; then
    old_pid="$(cat "${PID_FILE}" 2>/dev/null || true)"
    case "${old_pid}" in
        ''|*[!0-9]*) ;;
        *) kill -TERM "${old_pid}" 2>/dev/null || true ;;
    esac
    for _ in $(seq 1 30); do
        flock -n 9 && break
        sleep 0.1
    done
fi
flock -n 9 || exit 0
printf '%s\n' "$$" > "${PID_FILE}"

child=
cleanup() {
    trap - EXIT
    [ -z "${child}" ] || kill -TERM "${child}" 2>/dev/null || true
    if [ "$(cat "${PID_FILE}" 2>/dev/null || true)" = "$$" ]; then
        rm -f "${PID_FILE}"
    fi
}
trap cleanup EXIT
trap 'exit 0' HUP INT TERM

# Two Tint2 instances start together. Wait until Tint2 exists, then give the
# top panel enough time to claim the X11 notification area before docking.
while ! pgrep -u "$(id -u)" -x tint2 >/dev/null 2>&1; do
    sleep 1
done
sleep 3

while true; do
    pasystray &
    child=$!
    wait "${child}" || true
    child=
    sleep 2
done
