#!/usr/bin/env bash

# omarchy:summary=Show, set, or adjust focused monitor scaling
# omarchy:group=monitor
# omarchy:args=[up|down|SCALE]
# omarchy:examples=omarchy monitor scaling | omarchy monitor scaling 1.6 | omarchy monitor scaling up | omarchy monitor scaling down

case $("${BASH_SOURCE[0]%/*}/omarchy-compositor") in
  hyprland) exec "${BASH_SOURCE[0]%/*}/omarchy-hyprland-monitor-scaling" "$@" ;;
  sway) ;;
  *) exit 0 ;;
esac

# sway takes a fractional scale on any mode, so the presets apply as they are.
# Nothing is persisted: the output config decides the scale at the next login.
scales=(1 1.25 1.6 2 3 4)

usage() {
  echo "Usage: omarchy-monitor-scaling [up|down|SCALE]"
}

format_scale() {
  awk -v scale="$1" 'BEGIN { printf "%g\n", scale }'
}

case "${1:-}" in
"" | up | down) ;;
-h | --help)
  usage
  exit 0
  ;;
*)
  if [[ ! $1 =~ ^[0-9]+([.][0-9]+)?$ ]] ||
    ! awk -v scale="$1" 'BEGIN { exit !(scale >= 1 && scale <= 4) }'; then
    usage >&2
    exit 1
  fi
  ;;
esac

focused=$(swaymsg -t get_outputs -r 2>/dev/null | jq -c '[.[] | select(.focused == true)][0] // empty' 2>/dev/null)
[[ -n $focused ]] || { echo "No focused output" >&2; exit 1; }
name=$(jq -r '.name' <<<"$focused")
current=$(jq -r '.scale' <<<"$focused")

# The nearest preset to the current scale, one step up or down from it.
step_scale() {
  awk -v current="$current" -v direction="$1" -v list="${scales[*]}" '
    function distance(value) { value -= current; return value < 0 ? -value : value }
    BEGIN {
      count = split(list, presets, " ")
      best = 1
      for (i = 2; i <= count; i++) if (distance(presets[i]) < distance(presets[best])) best = i
      if (direction == "up" && best < count) best++
      if (direction == "down" && best > 1) best--
      print presets[best]
    }'
}

set_scale() {
  if [[ ! $name =~ ^[A-Za-z0-9._-]+$ ]]; then
    echo "Refusing unsafe monitor name" >&2
    exit 1
  fi

  swaymsg output "$name" scale "$1" >/dev/null || exit 1
  format_scale "$1"
}

case "${1:-}" in
"") format_scale "$current" ;;
up | down) set_scale "$(step_scale "$1")" ;;
*) set_scale "$1" ;;
esac
