#!/bin/bash

# We set the auto power-on flip-flop as AUTO_POWERON says; the values are
# described in /etc/default/helios64-auto-poweron.
AUTO_POWERON=on-power-loss
# shellcheck source=/dev/null
[[ -r /etc/default/helios64-auto-poweron ]] && . /etc/default/helios64-auto-poweron

case $AUTO_POWERON in
	always) arm=1 ;;
	never) arm=0 ;;
	*)
		arm=1
		# kexec skips U-Boot, so nothing would re-arm it
		if [[ $1 != boot && $1 != kexec ]]; then
			online=$(cat /sys/class/power_supply/gpio-charger/online)
			[[ $online == 0 ]] || arm=0
		fi
		;;
esac

# The flip-flop lines are GPIO4_D1 and GPIO4_D2; their global numbers
# depend on where the kernel places the gpio4 chip.
for chip in /sys/class/gpio/gpiochip*; do
	[[ $(cat "$chip/label") == gpio4 ]] && base=$(cat "$chip/base")
done
[[ -n $base ]] || exit 1

# AUTO_ON_D
d=$((base + 25))
# AUTO_EN_CLK
clk=$((base + 26))

# Export GPIO
[[ -e /sys/class/gpio/gpio$d ]] || echo $d > /sys/class/gpio/export
[[ -e /sys/class/gpio/gpio$clk ]] || echo $clk > /sys/class/gpio/export

echo out > /sys/class/gpio/gpio$d/direction
echo out > /sys/class/gpio/gpio$clk/direction

# Toggling the D Flip-Flop
echo $arm > /sys/class/gpio/gpio$d/value
echo 0 > /sys/class/gpio/gpio$clk/value
sleep 0.1
echo 1 > /sys/class/gpio/gpio$clk/value
sleep 0.1
echo 0 > /sys/class/gpio/gpio$clk/value
