#!/bin/sh
# Launch one cbar applet instance with its own plugin directory.
#
#   cosmic-tools-cbar-instance NAME
#
# cbar draws every plugin in its plugin directory inside ONE panel item, so a
# single instance cannot sit on the left, centre and right of a panel at once.
# To get separate items, start several cbar processes, each pointed at its own
# directory:
#
#   ~/.config/cosmic-tools/panel-bar/instances/NAME/
#
# CBAR_PLUGIN_DIR is cbar's supported knob for this. Do not try to separate
# instances with XDG_CONFIG_HOME: cbar builds its default plugin path from
# $HOME, so every instance would read the same directory.
#
# Each instance is registered with COSMIC through its own .desktop file
# (io.github.alexprates.CBar.<Name>.desktop, created by install.sh) whose Exec
# line calls this script. Several applets sharing cbar's Wayland app id works
# because cosmic-panel hands each applet its own pre-connected socket.
set -eu
name="${1:?usage: cosmic-tools-cbar-instance NAME}"
case "$name" in
    */*|.*) echo "invalid instance name: $name" >&2; exit 2 ;;
esac

CBAR_PLUGIN_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/cosmic-tools/panel-bar/instances/$name"
export CBAR_PLUGIN_DIR

CBAR="${CBAR_BIN:-}"
if [ -z "$CBAR" ]; then
    if [ -x "$HOME/.local/bin/cbar" ]; then CBAR="$HOME/.local/bin/cbar"
    else CBAR=$(command -v cbar || true)
    fi
fi
[ -n "$CBAR" ] || { echo "cbar not found; install it from https://github.com/alexandreprates/cbar" >&2; exit 1; }

# Output goes to /dev/null rather than the panel's pipe. The session may buffer
# child output without limit, and an applet stuck in an error loop can print
# enough to exhaust memory. Plugins are separate scripts, so nothing functional
# travels over cbar's stdout; to debug, run cbar by hand with CBAR_PLUGIN_DIR set.
exec "$CBAR" >/dev/null 2>&1
