#!/usr/bin/env bash
# capsled -- blink the Caps Lock LED
#
# (Avoid lib.bash as this is often called from /root/.profile or such.)

usage() {
	echo "Usage: ${0##*/} [count]"
	echo
	echo "By default, the LED returns to original state after blinking."
	echo "Suffixing count with + disables this."
}

shopt -s nullglob

n=${1:-1}			# number of blinks
t_on=${2:-0.1}			# on duration
t_off=${3:-0.1}			# off duration
restore=1			# whether to return back to original state

if [[ $n == *+ ]]; then
	n=${n%+}
	restore=0
fi

declare -a paths=(/sys/class/leds/*::capslock/brightness)
declare -A saved=()

do_restore() {
	for led in "${paths[@]}"; do
		echo ${saved[$led]-0} > $led
	done
}

do_save() {
	for led in "${paths[@]}"; do
		saved[$led]=$(< $led)
	done
}

if (( ! ${#paths[@]} )); then
	exit
fi

do_save
trap 'do_restore; exit' INT QUIT
max=$(( n*2 + restore ))
for (( i=1; i < max; i++ )); do
	for led in "${paths[@]}"; do
		echo $(( (i + saved[$led]) % 2 )) > $led
	done
	if (( i+1 == max )); then
		break
	elif (( i % 2 )); then
		sleep $t_on
	else
		sleep $t_off
	fi
done
if (( restore )); then
	do_restore
fi
