#!/usr/bin/env python3
# summary: Enroll, test, or remove your own fingerprints.
"""Usage: starchaser fingerprint status [USER] | enroll FINGER | test | remove | watch

Enroll or remove your own fingerprints. Enrollment prints JSON progress lines until it finishes.
"""
import ctypes
import json
import os
import re
import signal
import sys
from pathlib import Path

for lib in (Path(__file__).resolve().parents[1] / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (lib / "local_auth.py").is_file():
        sys.path.insert(0, str(lib))
        break
from local_auth import allowed
import subprocess
import sys

FINGERS = tuple(side + '-' + finger for side in ('left', 'right') for finger in ('thumb', 'index-finger', 'middle-finger', 'ring-finger', 'little-finger'))


def progress(line):
    if 'enroll-completed' in line:
        return 'Fingerprint added.'
    if 'enroll-stage-passed' in line:
        return 'Touch the reader again.'
    if any(word in line for word in ('retry', 'too-short', 'not-centered', 'remove-and-retry')):
        return 'Try again. Lift your finger, then touch the reader.'
    if any(word in line for word in ('failed', 'disconnected', 'no-space', 'duplicate')):
        return 'The fingerprint could not be added. Try another finger or use your password.'
    return ''


def status(user=None):
    import pwd
    user = __import__('pwd').getpwuid(os.getuid()).pw_name if user is None else pwd.getpwnam(user).pw_name
    result = subprocess.run(['fprintd-list', user], capture_output=True, text=True, timeout=15)
    text = result.stdout + result.stderr
    available = result.returncode == 0 and 'No devices' not in text
    return dict(ok=True, allowed=allowed(), available=available, fingers=[finger for finger in FINGERS if re.search(r'\b' + finger + r'\b', text)])


def watch():
    """Publish lid/dock changes from logind; do not keep waking the reader daemon."""
    import gi
    gi.require_version('Gio', '2.0')
    from gi.repository import Gio, GLib
    bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
    loop = GLib.MainLoop()
    def publish(*_):
        print(json.dumps(dict(allowed=allowed())), flush=True)
    def changed(connection, sender, path, interface, name, parameters, *_):
        iface, properties, invalidated = parameters.unpack()
        if iface == 'org.freedesktop.login1.Manager' and set(properties).union(invalidated) & {'LidClosed', 'Docked'}:
            publish()
    bus.signal_subscribe('org.freedesktop.login1', 'org.freedesktop.DBus.Properties', 'PropertiesChanged',
        '/org/freedesktop/login1', None, Gio.DBusSignalFlags.NONE, changed)
    bus.signal_subscribe('org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged',
        '/org/freedesktop/DBus', 'org.freedesktop.login1', Gio.DBusSignalFlags.NONE, publish)
    bus.connect('closed', lambda *_: (print(json.dumps(dict(allowed=False)), flush=True), loop.quit()))
    publish()
    loop.run()
    return 0


def require_normal_start():
    # Snapshot sessions use temporary fingerprints; identity changes would vanish at restart (decision 65).
    import bootsnap
    if bootsnap.booted() is not None:
        raise ValueError('This computer started from a snapshot, so nothing was changed. Restart normally first, or choose '
                         'Go back to this snapshot.')


def enroll(finger, testing=False):
    if not testing and finger not in FINGERS:
        raise ValueError('Choose a finger from the list.')
    if not testing:
        require_normal_start()
    parent = os.getppid()
    ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)
    if os.getppid() != parent:
        return 1
    command = ['fprintd-verify', __import__('pwd').getpwuid(os.getuid()).pw_name] if testing else ['fprintd-enroll', '-f', finger, __import__('pwd').getpwuid(os.getuid()).pw_name]
    child = subprocess.Popen(['stdbuf', '-oL', *command],
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    def stop(*_):
        raise SystemExit(1)
    signal.signal(signal.SIGTERM, stop)
    complete = False
    stages = 0
    # Bound an unattended or wedged reader operation, including a silent daemon.
    signal.signal(signal.SIGALRM, stop)
    signal.alarm(120)
    try:
        for line in child.stdout:
            message = progress(line)
            if testing:
                message = 'Fingerprint recognized.' if 'verify-match' in line else 'Fingerprint not recognized. Try again or use your password.' if 'verify-no-match' in line else ''
            if 'enroll-stage-passed' in line: stages += 1
            if message:
                complete |= ('verify-match' in line if testing else 'enroll-completed' in line)
                print(json.dumps(dict(ok=True, complete=complete, message=message, stages=stages)), flush=True)
        code = child.wait(timeout=5)
        if code or not complete:
            print(json.dumps(dict(ok=False, errors='Fingerprint not recognized. Try again or use your password.' if testing else "The fingerprint couldn't be added. Check the reader and try again.")), flush=True)
            return 1
        return 0
    finally:
        signal.alarm(0)
        if child.poll() is None:
            child.terminate()
            try:
                child.wait(timeout=3)
            except subprocess.TimeoutExpired:
                child.kill()
                child.wait()
        child.stdout.close()


def main(args):
    if args in (['--help'], ['-h'], ['help']):
        print(__doc__)
        return 0
    try:
        if len(args) in (1, 2) and args[0] == 'status':
            print(json.dumps(status(args[1] if len(args) == 2 else None)))
        elif len(args) == 2 and args[0] == 'enroll':
            return enroll(args[1])
        elif args == ['watch']:
            return watch()
        elif args == ['test']:
            return enroll('', testing=True)
        elif args == ['remove']:
            require_normal_start()
            result = subprocess.run(['fprintd-delete', __import__('pwd').getpwuid(os.getuid()).pw_name], capture_output=True, timeout=120)
            detail = (result.stderr or b'') + (result.stdout or b'')
            refused = any(word in detail.lower() for word in (b'permissiondenied', b'not authorized', b'cancel'))
            print(json.dumps(dict(ok=result.returncode == 0, message='Fingerprints removed.' if not result.returncode else 'Nothing was removed.' if refused else '', errors='' if not result.returncode or refused else "Couldn't remove fingerprints. Check the reader and try again.")))
            return 0 if not result.returncode else 1
        else:
            print(__doc__, file=sys.stderr)
            return 2
        return 0
    except (OSError, subprocess.SubprocessError, ValueError, KeyError) as error:
        print(json.dumps(dict(ok=False, errors=str(error) if isinstance(error, ValueError) else "The fingerprint reader didn't answer. Use your password or check again.")))
        return 1


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