#!/bin/bash

# omarchy:summary=Reload the Hyprland configuration, from inside or outside the session.

# Outside the session (ssh, a remotely started herdr) there is no instance
# signature, so reach the running Hyprland directly.
if [[ -n $HYPRLAND_INSTANCE_SIGNATURE ]]; then
  instance=()
else
  instance=(--instance 0)
fi

# Callers that run mid-update (such as omarchy-theme-refresh during migrations)
# opt in to skip reloading a compositor whose binary was replaced on disk,
# keeping omarchy-hyprland-reload-guard's suppression intact.
if [[ ${OMARCHY_RELOAD_SKIP_REPLACED:-} == "1" ]]; then
  proc_root="${OMARCHY_RESTART_HYPRCTL_PROC_ROOT:-/proc}"
  hypr_dir="${XDG_RUNTIME_DIR:-/run/user/$UID}/hypr"
  pid=""

  if [[ -n $HYPRLAND_INSTANCE_SIGNATURE ]]; then
    lock_file="$hypr_dir/$HYPRLAND_INSTANCE_SIGNATURE/hyprland.lock"
    if [[ -r $lock_file ]] && IFS= read -r candidate <"$lock_file" && [[ $candidate =~ ^[0-9]+$ ]]; then
      pid=$candidate
    fi
  else
    # Query hyprctl directly so the inspected PID and reloaded instance match.
    # If discovery yields no live instance, exit cleanly rather than reloading
    # an uninspected --instance 0.
    IFS=$'\t' read -r pid sig < <(hyprctl -j instances 2>/dev/null |
      jq -r '.[0] | select(.pid != null and .instance != null) | "\(.pid)\t\(.instance)"' 2>/dev/null)
    if [[ -z $pid || -z $sig ]]; then
      exit 0
    fi
    instance=(--instance "$sig")
  fi

  if [[ -n $pid && $(readlink "$proc_root/$pid/exe" 2>/dev/null) == *" (deleted)" ]]; then
    exit 0
  fi
fi

# With no Hyprland running there is nothing to reload; it reads the saved
# config when it starts, so that is not a failure for the caller.
hyprctl "${instance[@]}" reload >/dev/null 2>&1 || true
