#!/usr/bin/env bash
#
# Read battery status in FreeBSD
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# TODO: Which is better, apm or reading sysctls from hw.acpi.battery ?

# hw.acpi.battery.rate = milliwatts draining from battery
# hw.acpi.battery.time = minutes remaining

SLEEP_INTERVAL=${SLEEP_INTERVAL:-30}

while true; do
    battery_percentage=$(apm -l)
    battery_status=$(apm -b)
    seconds_remaining=$(apm -t)
    # minutes remaining would be at sysctl hw.acpi.battery.time
    class=""

    if [ $battery_status -eq 3 ]; then
        if [ $battery_percentage -eq 100 ]; then
            battery_icon="⚡"
        else
            battery_icon="⚡"
        fi
    elif [ $battery_percentage -le 12 ]; then
        battery_icon="⚠"
    elif [ $battery_percentage -le 25 ]; then
        battery_icon="▁"
    elif [ $battery_percentage -le 37 ]; then
        battery_icon="▂"
    elif [ $battery_percentage -le 50 ]; then
        battery_icon="▃"
    elif [ $battery_percentage -le 62 ]; then
        battery_icon="▄"
    elif [ $battery_percentage -le 75 ]; then
        battery_icon="▅"
    elif [ $battery_percentage -le 87 ]; then
        battery_icon="▆"
    elif [ $battery_percentage -lt 100 ]; then
        battery_icon="▇"
    else
        battery_icon="█"
    fi

    if [ $battery_percentage -le 15 ]; then
        class="critical"
    elif [ $battery_percentage -le 30 ]; then
        class="warning"
    fi

    if [ $seconds_remaining -eq -1 ]; then
        time_remaining="unknown time remaining."
    else
        time_remaining=$(printf '%dh:%dm:%ds\n' $((seconds_remaining/3600)) $((seconds_remaining%3600/60)) $((seconds_remaining%60)) )
    fi

    jq --unbuffered --compact-output <<EOF
{
"text":"${battery_percentage}% ${battery_icon}",
"tooltip":"${time_remaining}",
"percentage":${battery_percentage},
"class":"${class}"
}
EOF
    sleep $SLEEP_INTERVAL
done
