#!/bin/sh
# Hyprland window rule installer for Drovio's overlays (remote cursors,
# drawings, shared screen border): no blur behind them, input through them.
# Runs as the user and only touches their Hyprland configuration.
#
#   --status  prints one of: no-blur, installed, outdated (ours differs from
#             the shipped one: installing updates it), installable <config>,
#             manual (to add by hand), unknown
#   --manual  prints the rule to add by hand, in the running release's syntax
#   (none)    writes our rule file next to the configuration, appends the
#             lines loading it (after a backup), reloads, and rolls back if
#             the reload brings new configuration errors

set -u

# The rule files sit next to this script, in /opt/drovio as in the sources
resources=$(dirname "$0")
marker="drovio-overlay-rule"
config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/hypr"

fail() {
  echo "$1" >&2
  exit 1
}

running_hyprland() {
  [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] && command -v hyprctl >/dev/null 2>&1
}

# lua (hyprland.lua), blocks (hyprland.conf from 0.53, windowrule { }) or
# legacy (hyprland.conf before 0.53, windowrulev2)
syntax() {
  if hyprctl systeminfo 2>/dev/null | grep -q '^configProvider: lua'; then
    echo lua
    return
  fi
  # "0.56.2", or only a "v0.40.0" tag on older releases
  version=$(hyprctl -j version 2>/dev/null |
    sed -n 's/.*"\(version\|tag\)": *"v\{0,1\}\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\2 \3/p' |
    head -n 1)
  major=${version% *}
  minor=${version#* }
  if [ -n "$version" ] && { [ "$major" -gt 0 ] || [ "$minor" -ge 53 ]; }; then
    echo blocks
  else
    echo legacy
  fi
}

# Sets main (Hyprland's configuration), rule (our file) and resource (its
# source) for the given syntax
set_paths() {
  case $1 in
    lua)
      main="$config_dir/hyprland.lua"
      rule="$config_dir/drovio.lua"
      resource="$resources/hyprland-overlay-rule.lua"
      ;;
    *)
      main="$config_dir/hyprland.conf"
      rule="$config_dir/drovio.conf"
      resource="$resources/hyprland-overlay-rule.conf"
      ;;
  esac
}

# Our file as installing writes it
expected_rule() {
  # Escape what sed reads specially in a replacement
  main_escaped=$(printf '%s' "$main" | sed 's/[\\&|]/\\&/g')
  sed "s|@MAIN_CONFIG@|$main_escaped|" "$resource"
}

# Without the empty lines printed when there is none
config_errors() {
  hyprctl configerrors 2>/dev/null | sed '/^[[:space:]]*$/d'
}

status() {
  blur=$(hyprctl -j getoption decoration:blur:enabled 2>/dev/null)
  # A bool on recent releases, an int on older ones
  if echo "$blur" | grep -Eq '"(bool|int)": *(false|0)[ ,}]'; then
    echo no-blur
    return 0
  fi
  if ! echo "$blur" | grep -Eq '"(bool|int)": *(true|[1-9][0-9]*)[ ,}]'; then
    echo unknown
    return 1
  fi

  current=$(syntax)
  set_paths "$current"
  if [ "$current" = legacy ] || [ ! -f "$main" ]; then
    # A syntax we do not write, or a configuration we cannot find (--config)
    echo manual
  elif [ -f "$rule" ] && grep -q "$marker" "$main"; then
    if expected_rule | cmp -s - "$rule"; then
      echo installed
    else
      echo outdated
    fi
  else
    echo "installable $main"
  fi
}

manual() {
  current=$(syntax)
  if [ "$current" = legacy ]; then
    echo 'windowrulev2 = noblur, title:^drovio-overlay$'
    echo 'windowrulev2 = noshadow, title:^drovio-overlay$'
    echo 'windowrulev2 = nofocus, title:^drovio-overlay$'
    return
  fi
  set_paths "$current"
  # The rule alone, without our comments
  sed -e '/^[[:space:]]*\(#\|--\)/d' -e '/./,$!d' "$resource"
}

install_rule() {
  current=$(syntax)
  [ "$current" != legacy ] || fail "this Hyprland release is older than 0.53"
  set_paths "$current"
  [ -f "$main" ] || fail "cannot find $main"
  [ -f "$resource" ] || fail "cannot find $resource"

  errors_before=$(config_errors)

  backup="$main.bak.drovio-$(date +%s)"
  cp -p "$main" "$backup" || fail "cannot write $backup"

  expected_rule >"$rule.tmp" &&
    mv "$rule.tmp" "$rule" || {
    rm -f "$rule.tmp"
    fail "cannot write $rule"
  }

  # Appended, not rewritten: a configuration that is a symlink stays one
  if ! grep -q "$marker" "$main"; then
    if [ "$current" = lua ]; then
      # loadfile(), not dofile(): a deleted file just drops the rule, while
      # errors in it still get reported
      rule_lua=$(printf '%s' "$rule" | sed 's/[\\"]/\\&/g')
      printf '\n-- %s: keeps Drovio'\''s overlays from blurring the shared screen\nlocal drovio_overlay_rule = loadfile("%s")\nif drovio_overlay_rule then drovio_overlay_rule() end\n' \
        "$marker" "$rule_lua" >>"$main"
    else
      printf '\n# %s: keeps Drovio'\''s overlays from blurring the shared screen\nsource = %s\n' \
        "$marker" "$rule" >>"$main"
    fi || {
      rm -f "$rule"
      fail "cannot write $main"
    }
  fi

  hyprctl reload >/dev/null 2>&1

  # Errors the configuration already had are not ours
  new_error=$(config_errors | while IFS= read -r line; do
    printf '%s\n' "$errors_before" | grep -qxF -- "$line" || printf '%s\n' "$line"
  done | head -n 1)
  if [ -n "$new_error" ]; then
    cat "$backup" >"$main"
    rm -f "$rule"
    hyprctl reload >/dev/null 2>&1
    fail "Hyprland rejected the rule: $new_error"
  fi

  echo "rule in $rule, loaded from $main, copy of it in $backup"
}

running_hyprland || {
  echo unknown
  exit 1
}

case ${1:-} in
  --status) status ;;
  --manual) manual ;;
  "") install_rule ;;
  *) fail "usage: $0 [--status | --manual]" ;;
esac
