#!/bin/sh
# Aurora display controller (B9C). ST7735S on SPI via panel-mipi-dbi (DRM) -> fb0 -> fbcon (tty1) + MPP4 backlight.
#   aurora-display start   : wait for fb0, make sure the display pipe is enabled (fbcon takeover modeset, or one fbdev
#                            unblank if nothing enabled it), then switch the backlight on through the gpio-backlight driver.
#   aurora-display status  : one-line state summary
#   aurora-display bl on|off
# Never writes PMIC/GPIO registers directly: only fb0 'blank' and backlight sysfs attributes of the kernel drivers.
D=/run/aurora-display; L=$D/display.log; mkdir -p $D
FB=/sys/class/graphics/fb0; CON=/sys/class/drm/card0-SPI-1; BL=/sys/class/backlight/backlight
t() { cut -d' ' -f1 /proc/uptime; }
log() { echo "[$(t)] $*" >> $L; echo "[aurora-display] $*" > /dev/kmsg 2>/dev/null; }
fbcon_bound() { for v in /sys/class/vtconsole/vtcon*; do grep -q "frame buffer" $v/name 2>/dev/null && [ "$(cat $v/bind)" = 1 ] && return 0; done; return 1; }
l17_users() { for r in /sys/class/regulator/regulator.*; do [ "$(cat $r/name 2>/dev/null)" = l17 ] && { cat $r/num_users; return; }; done; echo 0; }
pipe_on() { [ "$(cat $CON/enabled 2>/dev/null)" = enabled ] && [ "$(cat $CON/dpms 2>/dev/null)" = On ] && [ "$(l17_users)" -ge 1 ]; }
state() { echo "fb0=$([ -e $FB ] && cat $FB/name) fbcon=$(fbcon_bound && echo bound || echo no) conn=$(cat $CON/enabled 2>/dev/null)/$(cat $CON/dpms 2>/dev/null) l17_users=$(l17_users) bl_power=$(cat $BL/bl_power 2>/dev/null) bl=$(cat $BL/actual_brightness 2>/dev/null)"; }
wait_for() { n=$1; shift; i=0; until "$@"; do i=$((i+1)); [ $i -ge $n ] && return 1; sleep 0.2; done; }
bl() {
	[ -d $BL ] || { log "FAIL: no backlight device"; return 1; }
	case $1 in
	on)  echo 0 > $BL/bl_power; echo 1 > $BL/brightness;;
	off) echo 0 > $BL/brightness;;
	esac
	log "backlight $1 -> bl_power=$(cat $BL/bl_power) actual_brightness=$(cat $BL/actual_brightness)"
}
case "$1" in
start)
	log "start: $(state)"
	wait_for 100 test -e $FB || { log "FAIL: fb0 did not appear within 20 s"; exit 1; }
	fbcon_bound && log "fbcon bound to fb0" || log "fbcon NOT bound (no framebuffer console)"
	if wait_for 25 pipe_on; then
		log "display pipe already enabled (by fbcon takeover) - no unblank needed"
	else
		log "display pipe not enabled -> fbdev unblank"
		echo 0 > $FB/blank
		wait_for 25 pipe_on || { log "FAIL: pipe still not enabled after unblank: $(state)"; exit 1; }
		log "display pipe enabled by unblank"
	fi
	bl on
	[ "$(cat $BL/actual_brightness)" = 1 ] || { log "FAIL: backlight did not turn on: $(state)"; exit 1; }
	log "=== DISPLAY READY $(state)";;
status) state;;
bl)	bl "$2";;
*)	echo "usage: $0 start|status|bl on|off"; exit 2;;
esac
