#!/bin/bash
# zephyrus-display primary | order — the laptop's internal panel among the outputs.
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
#
#   primary  makes the internal panel X's primary output, where the bars' tray goes.
#   order    the display key (Fn+F9, which the firmware sends as Super+P): odd workspaces to the
#            internal panel, even ones to the first external output, or all to the panel when it
#            is alone. The predecessor's orden-workspaces.
#
# The panel is found, not named: the connected output whose name starts with eDP. The predecessor
# wrote eDP-1, which is what this model calls it today and not a promise.
set -u
here=$(dirname "$0")
panel=$(xrandr --query 2>/dev/null | awk '$2 == "connected" && $1 ~ /^eDP/ { print $1; exit }')
[ -n "$panel" ] || { echo "zephyrus-display: no internal panel connected" >&2; exit 1; }
case "${1:-}" in
primary)
	exec xrandr --output "$panel" --primary
	;;
order)
	external=$(xrandr --listmonitors 2>/dev/null | awk -v p="$panel" 'NR > 1 && $NF != p { print $NF; exit }')
	[ -n "$external" ] || external=$panel
	# i3's workspace list, one object per workspace; num and output read from each. No jq: the
	# fields are flat strings and numbers, and rect, the only nested value, holds neither name.
	i3-msg -t get_workspaces 2>/dev/null | sed 's/},{"id"/}\n{"id"/g' |
		while read -r ws; do
			num=$(printf '%s' "$ws" | grep -o '"num":-\?[0-9]*' | cut -d: -f2)
			out=$(printf '%s' "$ws" | grep -o '"output":"[^"]*"' | cut -d'"' -f4)
			[ -n "$num" ] && [ "$num" -ge 0 ] || continue
			if [ $((num % 2)) -eq 0 ]; then dest=$external; else dest=$panel; fi
			[ "$out" = "$dest" ] && continue
			i3-msg "workspace number $num; move workspace to output $dest" >/dev/null
		done
	if [ "$external" = "$panel" ]; then
		"$here/zephyrus-notify" 7780 "Workspaces: all on the panel"
	else
		"$here/zephyrus-notify" 7780 "Workspaces: odd on the panel, even on $external"
	fi
	;;
*) echo "usage: zephyrus-display primary | order" >&2; exit 2 ;;
esac
