#!/bin/sh
# ANODE multi-monitor saved layout restorer (strict POSIX sh)
set -eu

: "${XDG_CONFIG_HOME:=$HOME/.config}"
CONF_FILE="$XDG_CONFIG_HOME/anode/displays.conf"

if [ -z "${DISPLAY:-}" ] || [ ! -r "$CONF_FILE" ] || ! command -v xrandr >/dev/null 2>&1; then
  exit 0
fi

XR_OUT="$(xrandr --query 2>/dev/null || true)"
if [ -z "$XR_OUT" ]; then
  exit 0
fi

SIG="$(printf '%s\n' "$XR_OUT" | awk '/ connected/ { print $1 }' | LC_ALL=C sort | awk '
  { s = (NR == 1) ? $0 : (s "," $0) }
  END { print s }
')"
if [ -z "$SIG" ]; then
  exit 0
fi

XR_SPEC="$(printf '%s\n' "$XR_OUT" | awk -v conf="$CONF_FILE" -v sig="$SIG" '
  BEGIN {
    cur_out = ""
  }
  /^[A-Za-z0-9._-]+ (connected|disconnected)/ {
    cur_out = ""
    if ($2 == "connected") {
      cur_out = $1
      conn[cur_out] = 1
    }
    next
  }
  cur_out != "" && /^[[:space:]]+[0-9]+x[0-9]+/ {
    mode = $1
    modes[cur_out SUBSEP mode] = 1
    next
  }
  END {
    hdr = "[profile:" sig "]"
    in_sec = 0
    en_cnt = 0
    out_cnt = 0
    while ((getline line < conf) > 0) {
      gsub(/\r$/, "", line)
      s = line
      gsub(/^[ \t]+|[ \t]+$/, "", s)
      if (s == "" || substr(s, 1, 1) == "#" || substr(s, 1, 1) == ";") continue
      if (substr(s, 1, 1) == "[") {
        if (in_sec) break
        in_sec = (s == hdr)
        continue
      }
      if (!in_sec || substr(s, 1, 7) != "output=") continue
      n = split(substr(s, 8), f, ",")
      if (n < 8) continue
      name = f[1]; en = f[2]; pri = f[3]; mode = f[4]
      hz = f[5]; px = f[6]; py = f[7]; rot = f[8]
      if (name !~ /^[A-Za-z0-9._-]+$/ || !(name in conn)) continue
      if (en != "0" && en != "1") continue
      if (pri != "0" && pri != "1") continue
      if (px !~ /^-?[0-9]+$/ || py !~ /^-?[0-9]+$/) continue
      if (rot != "normal" && rot != "left" && rot != "inverted" && rot != "right") continue

      if (en == "0") {
        rows[++out_cnt] = name "|0|0|-|-|0|0|normal"
        continue
      }
      has_mode = (mode ~ /^[0-9]+x[0-9]+$/ && ((name SUBSEP mode) in modes))
      if (!has_mode) mode = "auto"
      if (hz !~ /^[0-9]+(\.[0-9]+)?$/) hz = ""
      rows[++out_cnt] = name "|1|" pri "|" mode "|" hz "|" px "|" py "|" rot
      en_cnt++
    }
    close(conf)
    if (en_cnt < 1) exit 0
    for (i = 1; i <= out_cnt; i++) {
      print rows[i]
    }
  }
')"

if [ -z "$XR_SPEC" ]; then
  exit 0
fi

set --
OLD_IFS="$IFS"
IFS='
'
for row in $XR_SPEC; do
  _name="${row%%|*}"; _rest="${row#*|}"
  _en="${_rest%%|*}"; _rest="${_rest#*|}"
  _pri="${_rest%%|*}"; _rest="${_rest#*|}"
  _mode="${_rest%%|*}"; _rest="${_rest#*|}"
  _hz="${_rest%%|*}"; _rest="${_rest#*|}"
  _px="${_rest%%|*}"; _rest="${_rest#*|}"
  _py="${_rest%%|*}"; _rot="${_rest#*|}"

  set -- "$@" "--output" "$_name"
  if [ "$_en" = "0" ]; then
    set -- "$@" "--off"
    continue
  fi
  if [ "$_mode" = "auto" ]; then
    set -- "$@" "--auto"
  else
    set -- "$@" "--mode" "$_mode"
    if [ -n "$_hz" ] && [ "$_hz" != "-" ]; then
      set -- "$@" "--rate" "$_hz"
    fi
  fi
  set -- "$@" "--pos" "${_px}x${_py}" "--rotate" "$_rot"
  if [ "$_pri" = "1" ]; then
    set -- "$@" "--primary"
  fi
done
IFS="$OLD_IFS"

if [ $# -gt 0 ]; then
  xrandr "$@" >/dev/null 2>&1 || true
fi
