#!/bin/sh

MODEL=$(strings /proc/device-tree/model | tr ' ' '\n' | grep TS-)

if [ "${MODEL}" != "TS-7100-Z" ] && [ "${MODEL}" != "TS-7100" ]; then
	echo "Supercaps not supported on ${MODEL}"
	exit 0
fi

# This is extremely conservative, but allows running off
# of caps for ~10-15 seconds
RESET_PCT=90

# POWER_FAIL is:
GPIOCHIP="20ac000.gpio"
GPIOLINE="0"

# Check if the GPIO line is valid
if ! gpioget "${GPIOCHIP}" "${GPIOLINE}" >/dev/null 2>&1; then
	echo "Failed to get GPIO line ${GPIOLINE} on chip ${GPIOCHIP}"
	exit 1
fi

# while POWER_FAIL is high, check supercap levels
while true ; do
	# Read the GPIO line (this will set $gpio_value to 0 or 1)
	# While blocking on gpiomon could be used, it creates a subtle race
	# condition where we could miss a transition. Therefore, lets just
	# check the GPIO pin value every loop to ensure we have the latest
	# value. When the POWER_FAIL line is high, then we have lost power
	gpio_value=$(gpioget "${GPIOCHIP}" "${GPIOLINE}")

	if [ "${gpio_value}" -ne 1 ]; then
		sleep .5
		continue
	fi

	# Read the supercap percentage
	# The command below will return 1 if the charge level is above the
	# target percentage. Therefore a 0 is returned when the value has
	# fallen below the target
	if silabs scaps pct "${RESET_PCT}"; then
		wall "The script tssilomon has detected main power has been lost! Shutting down safely to prevent filesystem damage."
		reboot
		exit
	fi

	sleep 0.5
done
