#!/bin/sh

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

# Color  State     Meaning
# -----  -----     -------
#
# White  ON        Ethernet
#        FLASHING  WiFi
# Red    OFF       ONLINE
#        ON        NOT ONLINE

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"

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
}

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

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

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

	if [ -n "$ethernet" ]; then
		set_manual "$WHITE_TRIGGER" "$WHITE_BRIGHTNESS" 1
		set_manual "$RED_TRIGGER" "$RED_BRIGHTNESS" 0
	elif [ -n "$wifi" ]; then
		if has_trigger "$WHITE_TRIGGER" timer; then
			echo timer > "$WHITE_TRIGGER"
		else
			echo heartbeat > "$WHITE_TRIGGER"
		fi
		echo 1 > "$WHITE_BRIGHTNESS"
		set_manual "$RED_TRIGGER" "$RED_BRIGHTNESS" 0
	else
		set_manual "$WHITE_TRIGGER" "$WHITE_BRIGHTNESS" 0
		echo default-on > "$RED_TRIGGER"
		echo 1 > "$RED_BRIGHTNESS"
	fi

	sleep 1
done
