#!/bin/bash

# omarchy:summary=Set focused Hyprland monitor scaling to a specific value
# omarchy:args=<1|1.25|1.6|2|3|4>
# omarchy:examples=omarchy-hyprland-monitor-scaling-set 1.6 | omarchy-hyprland-monitor-scaling-set 2

NEW_SCALE="$1"

case "$NEW_SCALE" in
  1)    NEW_GDK_SCALE=1 ;;
  1.25) NEW_GDK_SCALE=1.25 ;;
  1.6)  NEW_GDK_SCALE=1.75 ;;
  2)    NEW_GDK_SCALE=2 ;;
  3)    NEW_GDK_SCALE=3 ;;
  4)    NEW_GDK_SCALE=4 ;;
  *)
    echo "Usage: omarchy-hyprland-monitor-scaling-set <1|1.25|1.6|2|3|4>" >&2
    exit 1
    ;;
esac

MONITOR_INFO=$(hyprctl monitors -j | jq -r '.[] | select(.focused == true)')
ACTIVE_MONITOR=$(echo "$MONITOR_INFO" | jq -r '.name')
WIDTH=$(echo "$MONITOR_INFO" | jq -r '.width')
HEIGHT=$(echo "$MONITOR_INFO" | jq -r '.height')
REFRESH_RATE=$(echo "$MONITOR_INFO" | jq -r '.refreshRate')

hyprctl eval "hl.monitor({ output = \"$ACTIVE_MONITOR\", mode = \"${WIDTH}x${HEIGHT}@${REFRESH_RATE}\", position = \"auto\", scale = $NEW_SCALE })" >/dev/null

# Persist to monitors.lua if the user still has Omarchy's generic catch-all
# defaults, so the scale survives reboots.
MONITOR_LUA="$HOME/.config/hypr/monitors.lua"
if [[ -f $MONITOR_LUA ]] && grep -q '^local omarchy_monitor_scale = ' "$MONITOR_LUA"; then
  sed -i -E \
    -e "s|^local omarchy_monitor_scale = .*|local omarchy_monitor_scale = ${NEW_SCALE}|" \
    -e "s|^local omarchy_gdk_scale = .*|local omarchy_gdk_scale = ${NEW_GDK_SCALE}|" \
    "$MONITOR_LUA"
elif [[ -f $MONITOR_LUA ]] && grep -Eq '^hl\.monitor\(\{ output = "", mode = "preferred", position = "auto", scale = ("auto"|[0-9.]+) \}\)' "$MONITOR_LUA"; then
  sed -i -E \
    -e "s|^(hl\.monitor\(\{ output = \"\", mode = \"preferred\", position = \"auto\", scale = )([^ ]+)( \}\))|\\1${NEW_SCALE}\\3|" \
    -e 's|^hl\.env\("GDK_SCALE", ".*"\)|hl.env("GDK_SCALE", "'"$NEW_GDK_SCALE"'")|' \
    "$MONITOR_LUA"
fi

notify-send -a omarchy-action -u low "󰍹    Display scaling set to ${NEW_SCALE}x"
