#!/bin/sh
# ocd-waybar-ctl: send a command to the ocd-waybar daemon.
# Usage: ocd-waybar-ctl {advance|lock|poll|quit}
# Wired into the waybar custom/ocd module as on-click / on-click-right.
#
# This must never hang: waybar runs it on a click and stops updating the
# module until it returns. socat's UNIX-SENDTO relay can block waiting on
# the datagram socket, so we use a small python sendto with a hard timeout
# instead. python3 is guaranteed present because the daemon itself needs it.

set -eu
cmd="${1:-advance}"
case "$cmd" in
  advance|lock|poll|quit) ;;
  *) echo "ocd-waybar-ctl: unknown command '$cmd'" >&2; exit 2 ;;
esac

sock="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/ocd-waybar.sock"
[ -S "$sock" ] || { echo "ocd-waybar-ctl: daemon socket not found at $sock" >&2; exit 1; }

python3 - "$sock" "$cmd" <<'PY'
import socket, sys
sock, cmd = sys.argv[1], sys.argv[2]
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
s.settimeout(2.0)
try:
    s.sendto((cmd + "\n").encode(), sock)
except (OSError, socket.timeout) as e:
    print("ocd-waybar-ctl: send failed: %s" % e, file=sys.stderr)
    sys.exit(1)
finally:
    s.close()
PY