#!/usr/bin/env python3
"""Fixed scheduler choices for Settings > Power; an event listener follows laptop power.

The loader owns scheduler processes so Game mode can temporarily switch and restore them.
Only root writes the computer's choice. No user-supplied command, path or arguments run as root.
"""
import fcntl
import json
import os
import re
import select
import shutil
import subprocess
import sys
import time
from pathlib import Path

CHOICE = Path('/var/lib/starchaser/scheduler.json')
RUNTIME = Path('/run/starchaser-scheduler')
SYSFS = Path('/sys/kernel/sched_ext')
SUPPLIES = Path('/sys/class/power_supply')
# Schedulers from Arch's scx-scheds, started through scx_loader's presets (scx-tools): bpfland favors interactive
# tasks; lavd's autopilot adapts to the load; its powersave mode packs work onto fewer cores.
MODES = {'responsive': ('bpfland', 'lowlatency'), 'balanced': ('lavd', 'auto'), 'battery': ('lavd', 'powersave')}


def read(path):
    try:
        return path.read_text().strip()
    except OSError:
        return ''


def load(path):
    try:
        value = json.loads(read(path))
        return value if isinstance(value, dict) else {}
    except ValueError:
        return {}


def write(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
    try:
        with tmp.open('w') as stream:
            json.dump(value, stream)
            stream.flush()
            os.fsync(stream.fileno())
        os.chmod(tmp, 0o644)
        tmp.replace(path)
    finally:
        tmp.unlink(missing_ok=True)


def choice():
    value = load(CHOICE).get('choice', 'automatic')
    return value if value in (*MODES, 'automatic') else 'automatic'


def on_battery():
    # Peripheral batteries (mice, headsets) must not turn a desktop into a laptop.
    devices = [p for p in SUPPLIES.glob('*') if read(p / 'scope') != 'Device']
    batteries = [p for p in devices if read(p / 'type') == 'Battery' and read(p / 'present') != '0']
    if not batteries:
        return False
    if any(read(p / 'online') == '1' for p in devices if read(p / 'type') != 'Battery'):
        return False
    return any(read(p / 'status') == 'Discharging' for p in batteries)


def target(value):
    return ('battery' if on_battery() else 'balanced') if value == 'automatic' else value


def unavailable():
    if not (SYSFS / 'state').exists():
        return "The kernel running now can't change how apps share processor time, so these choices are off. Restart and pick Starchaser kernel in the boot menu to use them."
    if not all(shutil.which(p) for p in ('scxctl', 'scx_lavd', 'scx_bpfland')):
        return 'The scheduler tools are missing. Install the scx-scheds and scx-tools packages to use these choices.'
    return ''


def loader_now():
    try:
        result = subprocess.run(['/usr/bin/scxctl', 'get'], capture_output=True, text=True, timeout=5)
        if result.returncode:
            raise RuntimeError("Couldn't read the scheduler service. Try again.")
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise RuntimeError("The scheduler service didn't answer. Try again.") from exc
    match = re.match(r'running (\w+) in (\w+) mode', result.stdout.strip(), re.I)
    if match:
        return [match[1].lower(), match[2].lower()]
    if result.stdout.strip() == 'no scx scheduler running':
        return []
    raise RuntimeError("Couldn't read the scheduler service. Try again.")


def attached(mode):
    return read(SYSFS / 'state') == 'enabled' and read(SYSFS / 'root/ops').startswith(MODES[mode][0])


def switch(mode):
    sched, preset = MODES[mode]
    try:
        sequence = read(SYSFS / 'enable_seq')
        verb = 'switch' if loader_now() else 'start'
        result = subprocess.run(['/usr/bin/scxctl', verb, '--sched', sched, '--mode', preset],
                                capture_output=True, text=True, timeout=15)
        if result.returncode:
            raise RuntimeError("Couldn't change the scheduler. The computer is still usable. Try again.")
        # A successful loader call can precede BPF attachment or a verifier failure.
        end = time.monotonic() + 8
        while time.monotonic() < end:
            if (read(SYSFS / 'enable_seq') not in ('', sequence)
                    and attached(mode) and loader_now() == [sched, preset]):
                return
            time.sleep(0.2)
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise RuntimeError("The scheduler service didn't answer. Try again.") from exc
    raise RuntimeError("The scheduler couldn't start on this kernel. Try another mode.")


def apply(value, defer=False):
    problem = unavailable()
    if problem:
        raise RuntimeError(problem)
    mode = target(value)
    previous = load(RUNTIME / 'active.json').get('mode', '')
    now = loader_now()
    # Game mode restores its saved loader preset when it ends. Wait for that instead of fighting it.
    if now and (previous not in MODES or now != list(MODES[previous])):
        if defer:
            return
        raise RuntimeError('Game mode or another scheduler is in control. Turn it off before changing this choice.')
    if previous == mode and now == list(MODES[mode]) and attached(mode):
        return
    try:
        switch(mode)
    except RuntimeError:
        # Restore the previous working mode if the new BPF program failed to attach.
        if previous in MODES:
            try:
                switch(previous)
            except RuntimeError:
                pass  # The kernel falls back to its standard scheduler; status reports the failure.
        raise
    write(RUNTIME / 'active.json', {'mode': mode})


def status():
    value = choice()
    problem = unavailable()
    active = load(RUNTIME / 'active.json').get('mode', '')
    running = ''
    if not problem:
        try:
            now = loader_now()
            if active in MODES and now == list(MODES[active]) and attached(active):
                running = active
            elif now and read(SYSFS / 'state') == 'enabled':
                problem = 'Game mode or another scheduler is in control. Your saved choice resumes when it ends.'
            else:
                problem = "The scheduler isn't running. The computer is using its standard scheduler."
        except RuntimeError as exc:
            problem = str(exc)
    return {'ok': True, 'choice': value, 'effective': target(value), 'active': running,
            'available': not unavailable(), 'message': problem}


def has_battery():
    return any(read(p / 'type') == 'Battery' and read(p / 'scope') != 'Device'
               for p in SUPPLIES.glob('*'))


def wait_for_loader():
    # At boot the loader service can be started before it answers; give it a short while instead of failing once.
    for _ in range(6):
        try:
            loader_now()
            return
        except RuntimeError:
            time.sleep(2)


def watch():
    # One event listener replaces repeated service starts. Laptops also recheck once a minute so an
    # automatic choice deferred during Game mode resumes afterward; desktops have no polling loop.
    monitor = subprocess.Popen(['/usr/bin/udevadm', 'monitor', '--udev', '--subsystem-match=power_supply'],
                               stdout=subprocess.PIPE)
    try:
        if not unavailable():
            wait_for_loader()
        if main(['apply'], quiet=True):
            return 1
        while monitor.poll() is None:
            ready, _, _ = select.select([monitor.stdout], [], [], 60 if has_battery() else None)
            if ready and not os.read(monitor.stdout.fileno(), 65536):
                break
            if main(['apply'], quiet=True):
                return 1
        return 1  # systemd restarts a monitor that exits or loses its event stream
    finally:
        if monitor.poll() is None:
            monitor.terminate()
        monitor.wait()


def main(args, quiet=False):
    if args in (['--help'], ['-h']):
        print('usage: starchaser scheduler get | set automatic|responsive|balanced|battery | apply')
        return 0
    if args == ['watch'] and os.geteuid() == 0:
        return watch()
    if args == ['get']:
        print(json.dumps(status()))
        return 0
    setting = len(args) == 2 and args[0] == 'set' and args[1] in (*MODES, 'automatic')
    if not setting and args != ['apply']:
        print('usage: starchaser scheduler get | set automatic|responsive|balanced|battery | apply', file=sys.stderr)
        return 2
    if os.geteuid() != 0:
        print(json.dumps({'ok': False, 'errors': 'Changing the scheduler needs administrator permission.'}))
        return 1
    RUNTIME.mkdir(parents=True, exist_ok=True)
    with (RUNTIME / 'lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            value = args[1] if setting else choice()
            apply(value, defer=not setting)
            if setting:
                write(CHOICE, {'choice': value})
            if not quiet:
                print(json.dumps(status()))
            return 0
        except (OSError, RuntimeError) as exc:
            message = str(exc) if isinstance(exc, RuntimeError) else "Couldn't save the scheduler choice. Try again."
            print(json.dumps({'ok': False, 'errors': message}))
            return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
