#!/bin/sh /etc/rc.common
# shellcheck shell=sh
# shellcheck disable=SC2034,SC3043
# procd service for the touchscreen UI.
#
# r01-ui owns /dev/fb0 and /dev/input/event0 once it starts. It also
# manages the backlight (saves the current value at launch, restores it
# on exit). On SIGTERM it blanks the panel and re-binds vtcon1 so the
# kernel framebuffer console comes back, then exits cleanly.
#
# Suppressed lints:
#   SC2034: USE_PROCD/START/STOP are contract vars consumed by /etc/rc.common
#   SC3043: OpenWrt busybox ash supports `local`, unlike strict POSIX sh

USE_PROCD=1
START=97
STOP=10

PROG=/usr/bin/r01-ui

start_service() {
	# Wait for fb0 and the touch evdev node to exist. They both come
	# from the kernel driver probe, usually <10 s after boot, but be
	# safe in case fbtft is loaded as a module.
	local i=0
	while [ ! -c /dev/fb0 ] || [ ! -c /dev/input/event0 ]; do
		i=$((i + 1))
		[ "$i" -gt 60 ] && {
			logger -t r01-ui "fb0 or event0 missing after 60s, giving up"
			return 1
		}
		sleep 1
	done

	procd_open_instance
	procd_set_param command "$PROG"
	procd_set_param env RUST_LOG=info
	procd_set_param stdout 1
	procd_set_param stderr 1
	# r01-ui handles SIGTERM gracefully (blanks fb, rebinds vtcon). Give
	# it 3 s before procd escalates to SIGKILL.
	procd_set_param term_timeout 3
	procd_set_param respawn 60 5 10
	procd_close_instance
}

reload_service() {
	# A UCI change → procd HUP → r01-ui re-reads /etc/config/r01-ui.
	procd_send_signal r01-ui '*' HUP
}

service_triggers() {
	procd_add_reload_trigger 'r01-ui'
}
