#!/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.
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() { timeout 5 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
elif ((open)) && [[ -n $screen && $popup_screen == "$screen" ]]; then
  ew update active-panel="$panel"
else
  ((open)) && ew close popup
  ew update active-panel="$panel" popup-screen="$screen"
  if [[ -n $screen ]]; then
    ew open popup --screen "$screen"
  else
    ew open popup
  fi
fi
