#!/usr/bin/env bash
# privacy-lock-watcher.sh
# Listens for systemd-logind "Session locked" signals via D-Bus and minimises
# any browser window showing the gallery (127.0.0.1:8500 or localhost:8500).
#
# Usage:
#   ./privacy-lock-watcher.sh &
#
# Requirements: dbus-monitor (dbus-tools), wmctrl or xdotool
#
# Home Assistant integration idea:
#   HA → shell_command: ssh user@machine "loginctl lock-session"
#   That triggers the D-Bus event below, which minimises the browser.

set -euo pipefail

GALLERY_PATTERN="127.0.0.1:8500\|localhost:8500\|tour-comfy"

minimize_gallery() {
    # Try xdotool first (works with most WMs)
    if command -v xdotool &>/dev/null; then
        xdotool search --name "$GALLERY_PATTERN" windowminimize --sync 2>/dev/null || true
        return
    fi
    # Fallback: wmctrl
    if command -v wmctrl &>/dev/null; then
        wmctrl -r "$GALLERY_PATTERN" -b add,hidden 2>/dev/null || true
        return
    fi
    echo "[privacy-lock-watcher] No window manager tool found (install xdotool or wmctrl)" >&2
}

echo "[privacy-lock-watcher] Listening for lock events on D-Bus..."

dbus-monitor --system "type='signal',interface='org.freedesktop.login1.Session'" 2>/dev/null \
| while IFS= read -r line; do
    if echo "$line" | grep -q '"Lock"'; then
        echo "[privacy-lock-watcher] Lock detected — minimising gallery window"
        minimize_gallery
    fi
done
