#!/usr/bin/env python3
"""Usage: starchaser-accessibility-input set SLOW BOUNCE MOUSE

Apply keyboard timing for the calling local active account. Values are on or off.
"""
import os
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from accessibility_input import active_seat, serve


def main(args):
    if args in (['--help'], ['-h']):
        print(__doc__)
        return 0
    if os.geteuid() != 0:
        return 1
    if len(args) == 5 and args[0] == 'serve' and args[1].isdigit() and all(a in ('on', 'off') for a in args[2:]) and 'PKEXEC_UID' not in os.environ:
        serve(int(args[1]), args[2] == 'on', args[3] == 'on', args[4] == 'on')
        return 0
    if len(args) != 4 or args[0] != 'set' or any(a not in ('on', 'off') for a in args[1:]):
        return 2
    uid = os.environ.get('PKEXEC_UID', '')
    if not uid.isdigit() or int(uid) < 1000 or not active_seat(int(uid)):
        return 1
    unit = 'starchaser-accessibility-input-' + uid
    # A missing previous service is fine; only this account's named service can be stopped.
    subprocess.run(['systemctl', 'stop', unit], capture_output=True, timeout=5)
    if 'on' in args[1:]:
        subprocess.run(['modprobe', 'uinput'], check=True, capture_output=True, timeout=5)
        subprocess.run(['systemd-run', '--unit=' + unit, '--collect', '--service-type=exec',
                        '-p', 'Restart=on-failure', '-p', 'TimeoutStopSec=2',
                        str(Path(__file__).resolve()), 'serve', uid, *args[1:]], check=True, capture_output=True, timeout=5)
    print('{"ok": true}')
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main(sys.argv[1:]))
    except (OSError, subprocess.SubprocessError):
        print('Keyboard timing could not be applied. Your physical keyboard is still available.', file=sys.stderr)
        sys.exit(1)
