#!/bin/sh
# DECIDE WHICH WAY UP THIS SCREEN IS — ONCE, AT BOOT.
#
# Kitchen displays get mounted portrait or landscape depending on the wall, and
# the same image has to serve both. Windows worked this out at boot on the
# PowerVision unit; so do we.
#
# Deliberately NOT continuous auto-rotate. A wall-mounted board that flips
# because a cook knocked it, mid-service, with twelve open tickets on it, is
# worse than one that is occasionally upside down until someone reboots it.
# Decide at boot, hold it for the session.
#
# Order of authority:
#   1. operator override      /etc/maestro-kds/orientation   (always wins)
#   2. accelerometer          one reading, if the board has one
#   3. panel's own hint       DRM panel_orientation property
#   4. native mode            a taller-than-wide panel is portrait
#
# Emits a wlroots transform on stdout: normal | 90 | 180 | 270
set -eu

OVERRIDE=/etc/maestro-kds/orientation

# ── 1. operator override ────────────────────────────────────────────────────
if [ -r "$OVERRIDE" ]; then
    v=$(tr -d '[:space:]' < "$OVERRIDE")
    case "$v" in
        normal|90|180|270) echo "$v"; exit 0 ;;
    esac
fi

# ── 2. accelerometer, read once ─────────────────────────────────────────────
# An all-in-one panel often carries an IIO accel. Gravity on X/Y tells us how
# the chassis is hung. We read it ONCE; nothing watches it afterwards.
for d in /sys/bus/iio/devices/iio:device*; do
    [ -r "$d/in_accel_x_raw" ] || continue
    x=$(cat "$d/in_accel_x_raw" 2>/dev/null || echo 0)
    y=$(cat "$d/in_accel_y_raw" 2>/dev/null || echo 0)
    ax=${x#-}; ay=${y#-}
    # Only trust it if one axis clearly dominates — a screen lying flat on its
    # back (which is how this unit was on the bench) gives a useless reading.
    if [ "$ax" -gt $(( ay * 2 )) ]; then
        [ "${x#-}" = "$x" ] && echo 270 || echo 90
        exit 0
    elif [ "$ay" -gt $(( ax * 2 )) ]; then
        [ "${y#-}" = "$y" ] && echo normal || echo 180
        exit 0
    fi
done

# ── 3. the panel's own orientation hint ─────────────────────────────────────
# Set by the kernel for panels known to be mounted rotated (quirk table + EDID).
for p in /sys/class/drm/card*-*/panel_orientation; do
    [ -r "$p" ] || continue
    case "$(cat "$p")" in
        "right side up") echo 90;  exit 0 ;;
        "left side up")  echo 270; exit 0 ;;
        "upside down")   echo 180; exit 0 ;;
    esac
done

# ── 4. native mode: taller than wide means the panel itself is portrait ─────
for m in /sys/class/drm/card*-*/modes; do
    [ -r "$m" ] || continue
    st=$(dirname "$m")/status
    [ "$(cat "$st" 2>/dev/null)" = "connected" ] || continue
    mode=$(head -1 "$m")
    w=${mode%%x*}; h=${mode##*x}; h=${h%%[!0-9]*}
    case "$w$h" in *[!0-9]*|"") continue ;; esac
    # A natively-portrait panel needs no transform; the compositor already
    # matches it. A landscape panel hung portrait is case 2 or 3, not this.
    echo normal; exit 0
done

echo normal
