#!/bin/bash
# omarchy:summary=Apply a display scale preset with 15s revert confirmation
# omarchy:args=<1.0|1.25|1.5|1.6|1.75|2.0>
# omarchy:examples=omarchycn display scale 1.6

set -euo pipefail

preset="${1:?usage: omarchycn display scale <1.0|1.25|1.5|1.6|1.75|2.0>}"

case "$preset" in
1.0 | 1.25 | 1.5 | 1.6 | 1.75 | 2.0) ;;
*)
  echo "Unknown preset: $preset (supported: 1.0 1.25 1.5 1.6 1.75 2.0)" >&2
  exit 1
  ;;
esac

monitors="$HOME/.config/hypr/monitors.lua"
if [[ ! -f $monitors ]]; then
  omarchy-refresh-config hypr/monitors.lua
fi

gdk=$(printf '%.0f' "$preset")
backup="$monitors.omarchycn-prev"
cp "$monitors" "$backup"

sed -i -E \
  -e "s|^local omarchy_monitor_scale = .*|local omarchy_monitor_scale = $preset|" \
  -e "s|^local omarchy_gdk_scale = .*|local omarchy_gdk_scale = $gdk|" \
  "$monitors"

if ! grep -q "omarchy_monitor_scale = $preset" "$monitors" ||
  ! grep -q "omarchy_gdk_scale = $gdk" "$monitors"; then
  mv "$backup" "$monitors"
  echo "monitors.lua lacks the omarchy scale lines; reverted, edit it manually" >&2
  exit 1
fi

echo "Monitor scale: $preset, GDK scale: $gdk"

if [[ -z ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then
  rm -f "$backup"
  echo "当前不在 Hyprland 会话内，重登录后生效"
elif ! hyprctl reload > /dev/null 2>&1; then
  mv "$backup" "$monitors"
  echo "hyprctl reload 失败，已恢复原配置" >&2
  exit 1
elif [[ -t 0 ]]; then
  echo "15 秒内按 y 保留新缩放，超时或按其他键自动恢复"
  if read -r -t 15 -n 1 answer && [[ $answer == "y" ]]; then
    rm -f "$backup"
    echo "已保留"
  else
    mv "$backup" "$monitors"
    hyprctl reload > /dev/null 2>&1
    echo "已恢复原缩放"
  fi
else
  omarchy-notification-send "OmarchyCN" "缩放已改为 $preset；如异常执行: mv $backup $monitors && hyprctl reload" 2> /dev/null || true
  echo "无终端交互：已应用；恢复命令: mv $backup $monitors && hyprctl reload"
fi
