#!/usr/bin/bash
# ABOUTME: Privileged helper invoked via pkexec from moonarch-batsaver-toggle.
# ABOUTME: Validates the threshold value and writes it to sysfs and the state file.

set -eu

VAL="${1:-}"

case "$VAL" in
    ""|*[!0-9]*)
        echo "Invalid argument: '$VAL' (expected integer 1-100)" >&2
        exit 1
        ;;
esac

if [ "$VAL" -lt 1 ] || [ "$VAL" -gt 100 ]; then
    echo "Out of range: $VAL (expected 1-100)" >&2
    exit 1
fi

THRESHOLD_FILE="/sys/class/power_supply/BAT0/charge_control_end_threshold"
STATE_DIR="/var/lib/moonarch"
STATE_FILE="$STATE_DIR/batsaver-threshold"

[ -f "$THRESHOLD_FILE" ] || { echo "No battery threshold support" >&2; exit 1; }

# Skip the kernel write when the value already matches — some Lenovo drivers
# reject same-value writes with EINVAL.
CURRENT=$(cat "$THRESHOLD_FILE")
if [ "$CURRENT" != "$VAL" ]; then
    printf %s "$VAL" > "$THRESHOLD_FILE"
fi

mkdir -p "$STATE_DIR"
printf %s "$VAL" > "$STATE_FILE"
