#!/bin/sh
#
# Copyright (C) 2026 SliTaz GNU/Linux - BSD License
# Author: Christophe Lincoln <pankso@slitaz.org>
# AI assistant: OpenCode
# Reviewer: Claude (Anthropic)
#
# lxtaz-ctrl-panel-setup — add Lxtaz Ctrl to the lxpanel slitaz profile.
# Usage: lxtaz-ctrl-panel-setup
#   Appends a single-click launchbar button (lxtaz-ctrl --toggle) at the
#   far right of ~/.config/lxpanel/slitaz/panels/panel, then restarts lxpanel.
#   The Button carries explicit image/tooltip/action so it works even though
#   lxpanel 0.10.1 logs "launchbar: desktop entry does not exist" for the id
#   lookup (proven end-to-end: single click opens the window).
# Idempotent: does nothing if an lxtaz-ctrl entry already exists.
# NOTE: the backup lives OUTSIDE panels/ on purpose — lxpanel loads every
# file in panels/ as a panel, so a .bak next to it would spawn a ghost
# duplicate bar overlapping the real one (all clicks/tests then hit the
# wrong instance; hours lost on this, Sep 2026).
# Restart rule: lxpanelctl restart often no-ops silently. Kill by PID, poll
# `pidof` until dead, then relaunch with setsid so it survives — otherwise
# the new instance hits "another systray already running" and runs crippled
# (no tray).
PANEL="$HOME/.config/lxpanel/slitaz/panels/panel"
BACKUP="$HOME/.config/lxpanel/slitaz/panel.bak-lxtaz-ctrl"

if [ ! -f "$PANEL" ]; then
	echo "lxtaz-ctrl-panel-setup: $PANEL not found, nothing to do." >&2
	exit 1
fi
if grep -q 'lxtaz-ctrl' "$PANEL"; then
	echo "lxtaz-ctrl-panel-setup: entry already present in $PANEL."
	exit 0
fi
cp -a "$PANEL" "$BACKUP" || exit 1
cat >> "$PANEL" <<'EOF'
Plugin {
  type=launchbar
  Config {
    Button {
      id=lxtaz-ctrl.desktop
      image=lxtaz-ctrl
      tooltip=Réglages rapides
      action=lxtaz-ctrl --toggle
    }
  }
}
EOF
if ! grep -q 'lxtaz-ctrl --toggle' "$PANEL"; then
	echo "lxtaz-ctrl-panel-setup: insert failed, restoring backup." >&2
	cp -a "$BACKUP" "$PANEL"
	exit 1
fi
echo "lxtaz-ctrl-panel-setup: launchbar button added to $PANEL (backup: $BACKUP)."
echo "Restart lxpanel WITH profile: kill by PID, poll pidof, then"
echo "  setsid lxpanel -p slitaz >/tmp/lxpanel.log 2>&1 </dev/null &"
echo "(bare 'lxpanel' loads the wrong profile: bottom bar, no style.
lxpanelctl restart no-ops; always verify single instance via pidof.)"
