#!/bin/sh
# Copyright (C) 2026 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Collect battery statistics for laptops (and, optionally, wireless peripherals)
# from the Linux kernel power supply class at /sys/class/power_supply.
#
# Each power supply that reports a type of "Battery" and matches the configured
# device classes is emitted as its own sub-section. The raw uevent file is
# dumped verbatim (KEY=VALUE lines), so the server side parser stays robust
# against kernel/driver differences in which POWER_SUPPLY_* fields are present.
#
# Device classes are distinguished via the kernel "scope" attribute:
#   - scope "Device"            -> a peripheral's own battery (e.g. a wireless
#                                  mouse/keyboard via the HID++ protocol,
#                                  exposed as hidpp_battery_*)
#   - scope "System" or absent  -> a system/laptop battery (e.g. BAT0/BAT1)

# Disable unused variable error (needed to keep track of version)
# shellcheck disable=SC2034
CMK_VERSION="3.0.0b1"

# Defaults when no bakery config is deployed: only system/laptop batteries,
# matching the primary use case. The agent bakery may override these via
# mk_lnx_battery.cfg.
DISCOVER_SYSTEM=true
DISCOVER_PERIPHERAL=false

CONFIG_FILE="${MK_CONFDIR}/mk_lnx_battery.cfg"
# shellcheck source=/dev/null
[ -r "${CONFIG_FILE}" ] && . "${CONFIG_FILE}"

main() {
    # No power supply class at all (e.g. headless servers, containers): stay silent.
    [ -d /sys/class/power_supply ] || return 0

    found=0
    for supply in /sys/class/power_supply/*; do
        [ -d "${supply}" ] || continue

        # Only batteries are of interest here, skip mains/AC adapters, USB, etc.
        [ "$(cat "${supply}/type" 2>/dev/null)" = "Battery" ] || continue

        # Classify by scope and honor the configured device classes.
        case "$(cat "${supply}/scope" 2>/dev/null)" in
            Device)
                [ "${DISCOVER_PERIPHERAL}" = "true" ] || continue
                ;;
            *)
                [ "${DISCOVER_SYSTEM}" = "true" ] || continue
                ;;
        esac

        uevent="${supply}/uevent"
        [ -r "${uevent}" ] || continue

        if [ "${found}" -eq 0 ]; then
            echo "<<<lnx_battery:sep(61)>>>"
            found=1
        fi

        # Use the directory name as a stable item identifier (e.g. BAT0).
        printf "[[[%s]]]\n" "$(basename "${supply}")"
        cat "${uevent}" 2>/dev/null
    done
}

main
