#!/bin/sh
# Turn every output off, or back on. Installed to /usr/local/bin/display-toggle and
# bound to the remote's power/sleep buttons in the Sway config.
#
# WHY THE POWER BUTTON DOES NOT POWER ANYTHING OFF: on a TV, that button turns the
# picture off. Here, `poweroff` would drop whatever game is running — unsaved — and
# take the room's screen away until somebody walks over to the machine. So the remote's
# power button does the thing the person pressing it actually meant.
#
# THE WAKE SIDE IS THE HARD HALF. With outputs powered off, Sway is still running and
# still receiving keys, so pressing power again lands here and turns them back on. That
# is why this is a toggle rather than two bindings: there is no other way back. It also
# means a stuck remote button cannot leave the screen dark — the next press fixes it.
#
# This is the local, no-network path. Home Assistant's "Display" switch goes through
# steamtv_agent/display_power.py instead, which also drives HDMI-CEC so the television
# itself goes to standby rather than just showing "no signal".
set -eu

# `swaymsg -t get_outputs` reports each output's power state in a field still named
# "dpms" (the *command* was renamed to `power`; the JSON key was not). If ANY output is
# still on, the intent of a press is "turn it off"; only when everything is already
# dark does a press mean "wake up". That ordering matters on a multi-output machine,
# where asking per-output would leave the remote toggling one screen at a time.
if swaymsg -t get_outputs | grep -q '"dpms": true'; then
  swaymsg 'output * power off'
else
  swaymsg 'output * power on'
fi
