#!/usr/bin/env sh
# SPDX-License-Identifier: MIT

# Require Busybox Ash or GNU Bash interpreter.
# 'set -e' isn't added intentionally to continue, if some LEDs are broken.

help() {
	local realname=$(realpath "$0")
	realname=${realname##*/}
	[ -L "$0" ] && echo "NOTE: ${0##*/} is a symlink. It is recommended to use '$realname' instead."
	echo "Usage: $realname [options] <state>"
	echo
	echo "Options:"
	echo "  -v      - Verbose mode"
	echo
	echo "Common states:"
	echo "  all     - turn on all indication LEDs"
	echo "  boot    - device is booting"
	echo "  busy    - operation is in progress"
	echo "  done    - operation is completed successfully"
	echo "  fail    - operation is failed"
	echo "  factory - factory is in progress"
	echo "  off     - turn off all indication LEDs"
	echo
	echo "Implementation-specific states:"
	echo "  re:[regex] - turn on only LEDs whose label matches given regex"
	echo "               in POSIX Basic Regular Expression format."
	echo
	echo "Examples:"
	echo
	echo "* Enable all LEDs that have either 'red' or 'blue' in their names:"
	echo "    $realname 're:red\|blue'"
	echo
	echo "* Enable LEDs 'ring1', 'ring12', and 'ring15':"
	echo "    $realname 're:ring\(1\|12\|15\)$'"
}

verbose() {
	[ $VERBOSE ] && echo "$@"
}

# This is snippet from 'help getopt' :)
O=$(getopt -l help -- hv "$@") || exit 1
eval set -- "$O"
while true; do
	case "$1" in
		-h|--help) help; exit 0;;
		-v) VERBOSE=1; shift;;
		--) shift; break;;
	esac
done

case "$1" in
	off) REGEX="^$";;
	all) REGEX=".*";;
	boot|busy) REGEX="red\|blue";;
	done) REGEX="green";;
	fail) REGEX="red";;
	factory) REGEX="red\|green";;
	re:*) REGEX="${1#re:}";;
	"") help; exit 0;;
	*) echo "Unknown state: '$1'" > /dev/stderr; exit 1;;
esac

verbose "Using regular expression: $REGEX"
REGEX="/sys/class/leds/.*\($REGEX\).*"

find /sys/class/leds/* -maxdepth 0 ! -name '*:sync' ! -regex "$REGEX" | while read -r; do
	verbose "Disable $REPLY"
	echo 0 > "$REPLY/brightness"
done

find /sys/class/leds/* -maxdepth 0 ! -name '*:sync' -regex "$REGEX" | while read -r; do
	verbose "Enable $REPLY"
	echo 255 > "$REPLY/brightness"
done
