#!/bin/sh
# Invoke After Detecting a DRM Hotplug: Only Fix When /sys/class/hdmi/.../hdmi_source Reports "mode set = no".
# log:/run/hdmi-hotplug.log
exec 1>>/run/hdmi-hotplug.log 2>&1
echo "=== $(date) === hotplug start: $1"
PATH=/usr/sbin:/usr/bin:/sbin:/bin

# Simple Debouncing: Skip Repeated Events Within 3 Seconds
LAST=/run/hdmi-hotplug.last
now=$(date +%s)
if [ -f "$LAST" ]; then
  last=$(cat "$LAST" 2>/dev/null || echo 0)
  [ $((now - last)) -lt 3 ] && { echo "debounce: skip"; exit 0; }
fi
echo "$now" > "$LAST"

# --- Read attr and determine the mode set column ---
ATTR=/sys/class/hdmi/hdmi/attr/hdmi_source
MODESET=$(awk -F'|' '
  /mode set/ { for(i=1;i<=NF;i++){t=$i;gsub(/^ +| +$/,"",t); if(t=="mode set") col=i } }
  /\| *state *\|/ && col { v=$col; gsub(/^ +| +$/,"",v); print v; exit }
' "$ATTR" 2>/dev/null)

[ -n "$MODESET" ] || MODESET=no  # Treat as "not set" if it cannot be read.
echo "mode_set=$MODESET"
[ "$MODESET" = "no" ] || { echo "already modeset, skip"; exit 0; }

# --- Select an available X cookie (prioritizing sddm, followed by the user's .Xauthority) and perform a quick self-check ---
XAUTH="$(ls -1t /var/run/sddm/* 2>/dev/null | head -n1)"
[ -n "$XAUTH" ] || XAUTH="$(ls -1t /home/*/.Xauthority 2>/dev/null | head -n1)"
if ! env -i PATH="$PATH" DISPLAY=:0 XAUTHORITY="$XAUTH" xrandr --query >/dev/null 2>&1; then
  echo "xrandr :0 not ready (XAUTH=$XAUTH)"; exit 0
fi

# --- Call your existing "second gear → auto" repair script (force execution once) ---
/usr/bin/hdmi-toggle-once force
echo "hotplug fix end"
