#!/usr/bin/env bash
# plank-primary-watch.sh
# Keep Plank pinned to the xrandr *primary* monitor.
#
# Plank's monitor='' ("primary") miscomputes its autohide reveal region on
# multi-head layouts, so we write the explicit connector name into Plank's
# `monitor` gsetting and restart Plank whenever the primary output changes
# OR its geometry (resolution/position) changes — either invalidates Plank's
# cached reveal region.

PLANK_PATH="net.launchpad.plank.dock.settings:/net/launchpad/plank/docks/dock1/"

# Connector name of the primary output, e.g. "DisplayPort-9".
primary_name() {
    xrandr --query | awk '/ connected primary/ {print $1; exit}'
}

# Change key: name + "WxH+X+Y" geometry. Changes if the primary moves/resizes.
primary_key() {
    xrandr --query | awk '/ connected primary/ {print $1, $4; exit}'
}

set_monitor() {
    # $1 = connector name; only write if it differs (avoids needless restarts)
    local want="$1" have
    have="$(gsettings get "$PLANK_PATH" monitor 2>/dev/null | tr -d \"\')"
    [ "$have" = "$want" ] || gsettings set "$PLANK_PATH" monitor "$want"
}

start_plank() {
    pgrep -x plank >/dev/null || setsid plank >/dev/null 2>&1 &
}

restart_plank() {
    pkill -x plank
    sleep 0.5
    setsid plank >/dev/null 2>&1 &
}

last="$(primary_key)"
name="$(primary_name)"
[ -n "$name" ] && set_monitor "$name"
start_plank

while true; do
    sleep 3
    cur="$(primary_key)"
    if [ -n "$cur" ] && [ "$cur" != "$last" ]; then
        last="$cur"
        set_monitor "$(primary_name)"
        restart_plank
    elif ! pgrep -x plank >/dev/null; then
        # Plank died (crash, manual kill) — bring it back.
        start_plank
    fi
done
