#!/usr/bin/python3
"""Read Linux battery status and enable IceWM's native percentage display."""

import argparse
import datetime
import os
from pathlib import Path
import re
import stat
import sys
import tempfile


SETTINGS = {
    "ShowTaskBar": "1",
    "TaskBarShowAPMStatus": "0",
    "TaskBarShowAPMAuto": "1",
    "TaskBarShowAPMTime": "0",
    "TaskBarShowAPMGraph": "0",
}


def read_value(path):
    try:
        return path.read_text().strip()
    except OSError:
        return None


def battery_status(root=Path("/sys/class/power_supply")):
    """Return real per-device readings; never combine incompatible capacity units."""
    readings = []
    if not root.exists():
        return readings
    for device in sorted(root.iterdir()):
        if read_value(device / "type") != "Battery":
            continue
        if read_value(device / "scope") == "Device":
            continue
        if read_value(device / "present") == "0":
            readings.append((device.name, None, "not present"))
            continue
        percent = None
        try:
            capacity = int(read_value(device / "capacity"))
            if 0 <= capacity <= 100:
                percent = capacity
        except (TypeError, ValueError):
            pass
        if percent is None:
            for unit in ("energy", "charge"):
                try:
                    now = int(read_value(device / (unit + "_now")))
                    full = int(read_value(device / (unit + "_full")))
                    if now >= 0 and full > 0:
                        percent = min(100, now * 100 // full)
                        break
                except (TypeError, ValueError):
                    pass
        readings.append((device.name, percent, read_value(device / "status") or "status unavailable"))
    return readings


def show_status(root=Path("/sys/class/power_supply")):
    readings = battery_status(root)
    if not readings:
        print("No system battery detected in /sys/class/power_supply.")
        return 0
    result = 0
    for name, percent, status in readings:
        if status == "not present":
            print(f"{name}: not present")
        elif percent is None:
            print(f"{name}: percentage unavailable; {status}")
            result = 1
        else:
            print(f"{name}: {percent}%; {status}")
    return result


def config_directory(env):
    """Match IceWM 4.0.0 YApplication::getPrivConfDir, including XDG fallback."""
    if env.get("ICEWM_PRIVCFG"):
        return Path(env["ICEWM_PRIVCFG"])
    home = Path(env.get("HOME") or Path.home())
    candidate = Path(env.get("XDG_CONFIG_HOME") or home / ".config") / "icewm"
    return candidate if candidate.is_dir() else home / ".icewm"


def update_settings(contents):
    pending = dict(SETTINGS)
    lines = []
    for line in contents.splitlines(keepends=True):
        match = re.match(r"^\s*(\w+)\s*=([^#\r\n]*)(.*?)(\r?\n)?$", line)
        if match and match[1] in SETTINGS:
            key = match[1]
            if key in pending:
                comment = (" " + match[3]) if match[3] else ""
                lines.append(f"{key}={pending.pop(key)}{comment}\n")
            continue
        lines.append(line)
    if pending:
        if lines and not lines[-1].endswith("\n"):
            lines[-1] += "\n"
        lines.append("# Tuxenix: show battery percentage when a system battery is present.\n")
        lines.extend(f"{key}={value}\n" for key, value in pending.items())
    return "".join(lines)


def enable_percentage(env=os.environ, system_dirs=(Path("/etc/icewm"), Path("/usr/share/icewm"))):
    if os.geteuid() == 0:
        raise ValueError("Run tuxenix-battery --enable as your desktop user, without sudo.")
    directory = config_directory(env)
    path = directory / "prefoverride"
    if path.is_symlink():
        raise ValueError(f"{path} is a symbolic link; edit its battery preferences manually.")
    existed = path.exists()
    mode = 0o600
    if existed:
        info = path.stat()
        if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid():
            raise ValueError(f"{path} must be a regular file owned by your desktop user.")
        mode = stat.S_IMODE(info.st_mode) & 0o777
    source = path if existed else next((d / "prefoverride" for d in system_dirs
                                        if (d / "prefoverride").is_file()), None)
    original = source.read_bytes() if source else b""
    updated = update_settings(original.decode("utf-8", "surrogateescape")).encode("utf-8", "surrogateescape")
    if existed and updated == original:
        print(f"Battery percentage is already enabled in {path}.")
        return path
    directory.mkdir(mode=0o700, parents=True, exist_ok=True)
    if existed:
        stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        fd, backup = tempfile.mkstemp(prefix=f"prefoverride.tuxenix-backup-{stamp}-", dir=directory)
        with os.fdopen(fd, "wb") as stream:
            stream.write(original)
            stream.flush()
            os.fsync(stream.fileno())
        print(f"Previous settings saved to {backup}")
    fd, temporary = tempfile.mkstemp(prefix=".prefoverride.tuxenix-", dir=directory)
    try:
        with os.fdopen(fd, "wb") as stream:
            stream.write(updated)
            os.fchmod(stream.fileno(), mode)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)
    print(f"Battery percentage enabled in {path}.")
    return path


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, epilog=(
        "With no arguments, read battery status only. --enable changes only your IceWM "
        "settings, keeps a backup when replacing a file, and can be repeated safely."))
    parser.add_argument("--enable", action="store_true", help="enable battery percentage in your IceWM taskbar (without sudo)")
    args = parser.parse_args(argv)
    try:
        if args.enable:
            enable_percentage()
            print("Apply with IceWM menu > Logout > Restart IceWM, or log out and run startx again.")
            print("The indicator appears only on systems with a detected battery.")
            show_status()
            return 0
        return show_status()
    except (OSError, ValueError) as error:
        print(f"tuxenix-battery: {error}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
