#!/bin/bash
if [ "${1}" != "poweroff" ]; then
	exit 0
fi

# The bq25895 chargers' ship mode prevents the battery from discharging
# even when the phone is powered off. This script is only useful
# on the Librem 5 phone:
if ! grep -qsi 'Librem 5' /sys/firmware/devicetree/base/model; then
	echo 'Not a Librem 5' >/dev/stderr
	exit 1
fi

# When a charger is connected, ship mode would prevent further charging
# when turned off. Disconnecting the charger later would of course
# result in the "old" behaviour of slowly discharging while powered off
# because ship mode is not set:
charging=$(cat /sys/class/power_supply/bq25890-charger-0/online)
if [ "$charging" -eq "1" ]; then
	echo 'Charger connected. Not setting ship mode.'
	exit 0
fi

# Only continue setting ship mode when running on battery.
# Connecting a charger will turn on the phone. The battery will
# not have been discharged in the meantime though:
echo 0 > /sys/class/power_supply/bq25890-charger-0/online
# shut off the battery with 10-15 second delay
i2cset -f -y 3 0x6a 0x09 0x6e
