#!/bin/sh

# led 12.0.1 (Khadas VIM)
# Copyright (c)2017-2026 John Lawson & Sons
# All Rights Reserved

# Color  State     Meaning
# -----  -----     -------
#
# White  ON        Ethernet
#        FLASHING  WiFi
# Red    OFF       NORMAL
#        FLASHING  NO NETWORK
#        ON        NO MONITOR/TV (WAITING)

RED_BRIGHTNESS="/sys/class/leds/red:status/brightness"
RED_TRIGGER="/sys/class/leds/red:status/trigger"
WHITE_BRIGHTNESS="/sys/class/leds/white:status/brightness"
WHITE_TRIGGER="/sys/class/leds/white:status/trigger"
DISPLAY_STANDBY_MARKER="/run/signage-display-standby"

has_trigger() {
	trigger_file="$1"
	trigger_name="$2"
	grep -Eq "(^|[[:space:]])\\[?$trigger_name\\]?([[:space:]]|$)" "$trigger_file"
}

set_manual() {
	trigger_file="$1"
	brightness_file="$2"
	value="$3"

	echo none > "$trigger_file"
	echo "$value" > "$brightness_file"
}

first_up_interface_by_prefix() {
	prefix="$1"

	for interface in /sys/class/net/"$prefix"*; do
		[ -e "$interface" ] || continue
		name=${interface##*/}
		[ "$name" = "lo" ] && continue
		if [ -f "$interface/operstate" ] && [ "$(cat "$interface/operstate")" = "up" ]; then
			echo "$name"
			return 0
		fi
	done

	return 1
}

monitor_connected() {
	found_connector=0

	for status_file in /sys/class/drm/card*-*/status; do
		[ -f "$status_file" ] || continue
		found_connector=1
		[ "$(cat "$status_file" 2>/dev/null)" = "connected" ] && return 0
	done

	# Do not report a missing monitor when this kernel exposes no DRM status.
	[ "$found_connector" -eq 0 ] && return 0
	return 1
}

set_red_off() {
	set_manual "$RED_TRIGGER" "$RED_BRIGHTNESS" 0
}

set_red_on() {
	set_manual "$RED_TRIGGER" "$RED_BRIGHTNESS" 1
}

set_red_flashing() {
	if has_trigger "$RED_TRIGGER" timer; then
		echo timer > "$RED_TRIGGER"
	else
		echo heartbeat > "$RED_TRIGGER"
	fi
	echo 1 > "$RED_BRIGHTNESS"
}

[ -f "$RED_TRIGGER" ] || exit 0
[ -f "$WHITE_TRIGGER" ] || exit 0

set_manual "$RED_TRIGGER" "$RED_BRIGHTNESS" 0
set_manual "$WHITE_TRIGGER" "$WHITE_BRIGHTNESS" 0

last_state=""

while :; do
	ethernet=$(first_up_interface_by_prefix e || true)
	wifi=$(first_up_interface_by_prefix w || true)

	if [ -e "$DISPLAY_STANDBY_MARKER" ] || ! monitor_connected; then
		state="display-off"
	elif [ -n "$ethernet" ]; then
		state="ethernet"
	elif [ -n "$wifi" ]; then
		state="wifi"
	else
		state="offline"
	fi

	if [ "$state" != "$last_state" ]; then
		case "$state" in
			display-off)
				set_manual "$WHITE_TRIGGER" "$WHITE_BRIGHTNESS" 0
				set_red_on
				;;
			ethernet)
				set_manual "$WHITE_TRIGGER" "$WHITE_BRIGHTNESS" 1
				set_red_off
				;;
			wifi)
				if has_trigger "$WHITE_TRIGGER" timer; then
					echo timer > "$WHITE_TRIGGER"
				else
					echo heartbeat > "$WHITE_TRIGGER"
				fi
				echo 1 > "$WHITE_BRIGHTNESS"
				set_red_off
				;;
			offline)
				set_manual "$WHITE_TRIGGER" "$WHITE_BRIGHTNESS" 0
				set_red_flashing
				;;
		esac
		last_state="$state"
	fi

	sleep 1
done
