#!/usr/bin/env python3
# summary: Read or change the computer's scheduler choice.
"""Read the live scheduler or change the computer's saved choice through its privileged helper."""
import json
import subprocess
import sys

HELPER = '/usr/local/lib/starchaser/starchaser-scheduler'


def main(args):
    if args in (['--help'], ['-h'], ['help']) or any(a in ('-h', '--help') for a in args[1:]):      # help after a command word too
        print('''Usage: starchaser scheduler get | set automatic|responsive|balanced|battery

Choose how running apps share processor time, alongside Power mode.
You can also change this in Settings > Power > Sharing processor time.

  automatic   Recommended default: balanced when plugged in, battery on an unplugged laptop.
  responsive  Favor quick reactions from apps.
  balanced    Handle everyday work with a balance of speed and energy use.
  battery     Save power; also works on a desktop without a battery.

get prints JSON: choice is the saved setting, effective is the mode that setting
calls for now, and active is the mode actually running (empty if none is running).
Game mode or another scheduler can temporarily take control.
set saves a choice and applies it without restarting; administrator permission is required.''')
        return 0
    if args == ['get']:
        command = [HELPER, 'get']
    elif len(args) == 2 and args[0] == 'set' and args[1] in ('automatic', 'responsive', 'balanced', 'battery'):
        command = ['pkexec', HELPER, *args]
    else:
        modes = ('automatic', 'responsive', 'balanced', 'battery')
        if not args or args[0] not in ('get', 'set'):
            reason = f"unknown command {args[0]!r}." if args else 'missing command.'
        elif args[0] == 'get':
            reason = 'get takes nothing after it.'
        elif len(args) == 1:
            reason = f"set needs a mode: {', '.join(modes)}."
        elif len(args) > 2:
            reason = f"set takes one mode (got {len(args) - 1} words)."
        else:
            reason = f"{args[1]!r} is not a mode (choose from {', '.join(modes)})."
        print(f"starchaser scheduler: {reason} Run 'starchaser scheduler --help' for more help.", file=sys.stderr)
        return 2
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=45)
    except (OSError, subprocess.TimeoutExpired):
        print(json.dumps({'ok': False, 'errors': "Couldn't read or change the scheduler. Check that the scheduler service is installed and permission was granted."}))
        return 1
    try:
        value = json.loads(result.stdout)
        if not isinstance(value, dict):
            raise ValueError('shape')
    except ValueError:
        # pkexec answers on stderr when nothing could ask for the password (a script, a remote shell): say that,
        # not to check a service that is installed and running. Same words as the sibling tools' pkexec refusals.
        text = (result.stderr or '').lower()
        if result.returncode == 126:
            errors = 'Not changed: you closed the password box.'
        elif 'authentication agent' in text or '/dev/tty' in text:
            errors = "No password window opened, so the change didn't start. Sign out and back in, then try again."
        elif result.returncode == 127 and ('pkexec' in text or 'authoriz' in text or 'authentication' in text):
            errors = "Couldn't get permission. Try again; if no password box appears, sign out and back in."
        else:
            errors = "Couldn't read or change the scheduler. Check that the scheduler service is installed and permission was granted."
        print(json.dumps({'ok': False, 'errors': errors}))
        return 1
    print(json.dumps(value))
    return result.returncode


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