#!/bin/sh
#
# Copyright (C) 2024-2025 Claes Nästén <pekdon@gmail.com>
#

battery="100"
battery_state="ac"
battery_count="0"

read_openbsd_apm()
{
	apm_status=`apm | sed 's/,//' | sed 's/%//'`
	battery_info=`echo "$apm_status" | awk '/Battery state: / { print $3 }'`
	if test "x${battery_info}" = "xabsent"; then
		battery_count="0"
	else
		battery_count="1"
		battery=`echo "$apm_status" \
			| awk 'BEGIN { p=0 } END { print p } /Battery state: / { p=$4 }'`
		battery_state=`echo "$apm_status" | grep 'AC adapter state: ' \
			| sed 's/.*: //' | tr ' ' '_'`
		if test "x${battery_state}" = "xnot_connected"; then
			battery_state="battery"
		else
			battery_state="ac"
		fi
	fi
}

read_netbsd_envstat()
{
	battery_info=`envstat | awk \
		'BEGIN { battery="100"; battery_count="0" ; battery_state="ac" } \
		/^\[acpiacad[0-9+]\]/ { in_ac=1; in_bat=0 } \
		/connected:/ { if (in_ac && $2 == "FALSE") { battery_state="battery" } } \
		/^\[acpibat[0-9]+\]/ { in_bat=1; in_ac=0; battery_count += 1 } \
		/charge:/ { if (in_bat) { battery=substr($6, 2, length($6) - 3) } } \
		END { print battery " " battery_state " "  battery_count  }'`
	battery=`echo $battery_info | awk '{ print int($1) }'`
	battery_state=`echo $battery_info | awk '{ print $2 }'`
	battery_count=`echo $battery_info | awk '{ print $3 }'`
}

read_sysfs()
{
	bat0="/sys/class/power_supply/BAT0"
	if ! test -e "$bat0"; then
		return
	fi

	battery=`cat "$bat0/capacity"`
	battery_state=`cat "$bat0/status" | tr A-Z a-z`
	if test "x${battery_state}" = "xdischarging"; then
		battery_state="battery"
	else
		battery_state="ac"
	fi
	battery_count=`ls /sys/class/power_supply/BAT* | wc -l`
}

UNAME_S="$1"
if test "x${UNAME_S}" = "x"; then
	UNAME_S=`uname -s`
fi

case $UNAME_S in
	OpenBSD)
		read_openbsd_apm
		;;
	NetBSD)
		read_netbsd_envstat
		;;
	Linux)
		read_sysfs
		;;
	*)
		;;
esac

echo "battery $battery"
echo "battery_count $battery_count"
echo "battery_state $battery_state"
