#!/usr/bin/env python3
"""Narrowly scoped root helper for supported TuxArmory sysfs writes across laptop vendors."""
import re
import sys
from pathlib import Path


def main() -> int:
    if len(sys.argv) != 3:
        print("usage: tux-armory-sysfs-helper SETTING VALUE", file=sys.stderr)
        return 2
    setting, value = sys.argv[1:]
    if setting == "platform_profile":
        path = Path("/sys/firmware/acpi/platform_profile")
        choices = Path("/sys/firmware/acpi/platform_profile_choices")
        if not re.fullmatch(r"[a-zA-Z0-9_-]+", value) or value not in choices.read_text().split():
            print("unsupported platform profile", file=sys.stderr)
            return 2
    elif setting in ("charge_control_end_threshold", "charge_control_start_threshold", "charge_stop_threshold", "charge_start_threshold"):
        path = next((p / setting for p in sorted(Path("/sys/class/power_supply").glob("BAT*"))
                     if (p / setting).is_file()), None)
        if path is None or not value.isdecimal() or not 1 <= int(value) <= 100:
            print("invalid battery charge limit", file=sys.stderr)
            return 2
    elif setting == "conservation_mode":
        candidates = (
            Path("/sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode"),
            Path("/sys/bus/platform/drivers/ideapad_laptop/VPC2004:00/conservation_mode"),
            Path("/sys/bus/platform/devices/VPC2004:00/conservation_mode"),
        )
        path = next((c for c in candidates if c.is_file()), None)
        if path is None or value not in ("0", "1"):
            print("invalid Lenovo conservation mode value", file=sys.stderr)
            return 2
    elif setting == "kbd_brightness":
        candidates = sorted(Path("/sys/class/leds").glob("*kbd*")) + sorted(Path("/sys/class/leds").glob("*::kbd_backlight"))
        led = next((c for c in candidates if (c / "brightness").is_file()), None)
        path = (led / "brightness") if led else None
        if path is None or not value.isdecimal():
            print("invalid keyboard brightness", file=sys.stderr)
            return 2
    else:
        print("unsupported sysfs setting", file=sys.stderr)
        return 2
    try:
        path.write_text(value, encoding="utf-8")
    except OSError as exc:
        print(f"cannot write sysfs setting: {exc}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
