#!/bin/sh
# acc - show charging status, voltage and current.
# Output layout borrowed from ACC's `acc -i`. Usage: acc -i

CHARGER=/sys/class/power_supply/pm8150b-charger
BATTERY=/sys/class/power_supply/qcom-battery

[ "$1" = "-i" ] || {
	echo "usage: $(basename "$0") -i" >&2
	exit 2
}

calc() { awk "BEGIN { printf \"%.2f\", $* }"; }

is_num() { case "$1" in ''|*[!0-9-]*) return 1;; esac; }

cap=$(cat "$BATTERY/capacity" 2>/dev/null)
# qcom-battery 的 status 不可靠，放电时报 Charging，
# 以充电 IC 自己的 status 为准。
status=$(cat "$CHARGER/status" 2>/dev/null)
temp=$(cat "$BATTERY/temp" 2>/dev/null)
enabled=$(cat "$CHARGER/charging_enabled" 2>/dev/null)
online=$(cat "$CHARGER/online" 2>/dev/null)
volt=$(cat "$BATTERY/voltage_now" 2>/dev/null)
curr=$(cat "$BATTERY/current_now" 2>/dev/null)

if is_num "$temp"; then temp_s="$((temp / 10))℃"; else temp_s="n/a"; fi

if is_num "$volt"; then volt_s="$(calc "$volt / 1000000")V"; else volt_s="n/a"; fi
if is_num "$curr"; then curr_s="$(calc "$curr / 1000000")A"; else curr_s="n/a"; fi
if [ "$volt_s" = n/a ] || [ "$curr_s" = n/a ]; then
	pow_s="n/a"
else
	pow_s="$(calc "$curr / 1000000 * $volt / 1000000")W"
fi

{
	printf 'level %s%%\n' "${cap:-n/a}"
	printf 'status %s\n' "${status:-n/a}"
	printf 'temp %s\n' "$temp_s"
	printf 'charging_enabled %s\n' "${enabled:-n/a}"

	printf '\ncurrent_now %s\nvoltage_now %s\npower_now %s\n' "$curr_s" "$volt_s" "$pow_s"

	if [ "$online" = 1 ]; then
		ps_type=$(cat "$CHARGER/type" 2>/dev/null)
		ps_amps=$(cat "$CHARGER/current_now" 2>/dev/null)
		ps_volts=$(cat "$CHARGER/voltage_now" 2>/dev/null)

		if is_num "$ps_amps" && is_num "$ps_volts"; then
			pa="$(calc "$ps_amps / 1000000")A"
			pv="$(calc "$ps_volts / 1000000")V"
			pw="$(calc "$ps_amps / 1000000 * $ps_volts / 1000000")W"
			if [ "$pow_s" != n/a ]; then
				cw="$(calc "${pw%W} - ${pow_s%W}")W"
			else
				cw="n/a"
			fi
			printf '\ncharge_type %s\npower_supply_amps %s\npower_supply_volts %s\npower_supply_watts %s\nconsumed_watts %s\n' \
				"${ps_type:-n/a}" "$pa" "$pv" "$pw" "$cw"
		else
			printf '\ncharge_type %s\npower_supply n/a\n' "${ps_type:-n/a}"
		fi
	fi

	printf '\n'
	(cd /sys/class/power_supply && grep . */online 2>/dev/null | sed -E 's/:(.)$/ \1/')
}
