#!/usr/bin/env bash
# Toggle a panel of the popup window on the focused monitor.
#
# The popup hosts every panel behind revealers, so switching panels while it
# is open is just a variable update (animated, no scripts restarted).  It is
# only closed and re-opened when it has to move to another monitor.
#
# `eww open popup` takes longer than the client's 100 ms reply deadline, so
# its exit status and error output are meaningless and ignored (the daemon
# carries the command out anyway; the lib's eww wrapper makes sure a slow
# reply can never spawn a second daemon).
panel=$1
[[ -n $panel ]] || exit 64

# One toggle at a time; the lock dies with this process.  fd 9 is closed for
# every eww call so nothing can inherit it.
exec 9>"${XDG_RUNTIME_DIR:-/tmp}/eww-panel-toggle.lock"
flock -n 9 || exit 0

ew() { eww "$@" 9>&-; }

current=$(ew get active-panel 2>/dev/null | tr -d '"')
popup_screen=$(ew get popup-screen 2>/dev/null | tr -d '"')
screen=$(eww-bar focused)
if ew active-windows 2>/dev/null | grep -qx 'popup: popup'; then open=1; else open=0; fi

if ((open)) && [[ $current == "$panel" ]]; then
  ew update active-panel=
  ew close popup 2>/dev/null
elif ((open)) && [[ -n $screen && $popup_screen == "$screen" ]]; then
  ew update active-panel="$panel"
else
  ((open)) && ew close popup 2>/dev/null
  ew update active-panel="$panel" popup-screen="$screen"
  if [[ -n $screen ]]; then
    ew open popup --screen "$screen" >/dev/null 2>&1
  else
    ew open popup >/dev/null 2>&1
  fi
fi
exit 0
