#!/usr/bin/env python3
# summary: Manage desktop app permissions and privacy history.
"""Usage: starchaser permissions status | set APP camera|microphone|location|files|screen on|off
       starchaser permissions restore APP
       starchaser permissions master camera|microphone|location|screen on|off | clear-history

Manage desktop app permissions. Restricted native apps use a separate private profile. Reopen apps after changes.
Screen and file grants can be revoked; the next request asks again. Close and reopen an open app after a sandbox change.
Blocking microphone access also blocks that sandbox app's sound playback.
"""
import configparser
import fcntl
import io
import json
import os
import re
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_app_privacy as native
from starchaser_device_io import CONFIG, STATE, read_json, run, update_json, write_json

PREFS = CONFIG / 'starchaser/permissions.json'
HISTORY = STATE / 'starchaser/privacy-history.json'
REQUESTS = STATE / 'starchaser/privacy-requests.json'
APP = re.compile(r'[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*){2,}\Z')
CATEGORIES = ('camera', 'microphone', 'location', 'screen', 'files')


def apps():
    out = {}
    for line in run('flatpak', 'list', '--app', '--columns=application,name').splitlines():
        key, _, name = line.partition('\t')
        if APP.fullmatch(key):
            out[key] = name or key
    return out


def permissions():
    rows = []
    for line in run('flatpak', 'permissions').splitlines():
        fields = line.split('\t')
        if len(fields) < 4:
            fields = line.split(None, 4)
        if len(fields) >= 4 and APP.fullmatch(fields[2]):
            rows.append(dict(table=fields[0], object=fields[1], app=fields[2], permission=fields[3]))
    return rows


def history():
    value = read_json(HISTORY)
    return value if isinstance(value, dict) else {}


def record_use(observation, now=None):
    stamp = int(time.time() if now is None else now)
    def change(saved):
        dirty = False
        for category, users in observation.items():
            key = 'microphone' if category == 'mic' else category
            if key not in CATEGORIES:
                continue
            for user in users:
                if user.get('recent') or user.get('test'):
                    continue
                name = user.get('app', '')
                if not isinstance(name, str) or not name:
                    continue
                used = saved.setdefault(key, {})
                if stamp - used.get(name, 0) >= 60 or name not in used:
                    used[name] = stamp
                    dirty = True
                # Bound history by the most recent app names; never retain a file path or device serial.
                if len(used) > 200:
                    del used[min(used, key=used.get)]
        return dirty
    # Most frames do not change an app's minute. Avoid rewriting state on every audio graph change.
    current = history()
    trial = json.loads(json.dumps(current))
    if change(trial):
        update_json(HISTORY, change)


def clear_history():
    update_json(HISTORY, lambda saved: saved.clear())


def forget_unsaved_recording(recordings=None):
    """Drop "Last used by Screen recorder" when no recording was saved at or after that time.

    Starchaser's own recorder always leaves a file in ~/Videos/Recordings that it writes until the recording ends,
    so a real use has a recording modified at or after the stamp. A start that failed at once (basic graphics) left
    a stamp and no file, and the gray Screen light then claimed a recording for good, even after a restart.
    Deleting the recording also forgets its use, which is all the light could have pointed to."""
    folder = Path(recordings) if recordings else Path.home() / 'Videos/Recordings'
    stamp = history().get('screen', {}).get('Screen recorder')
    if not isinstance(stamp, (int, float)):
        return False
    try:
        for video in folder.glob('*.mp4'):
            info = video.stat()
            if info.st_size and info.st_mtime >= stamp - 5:
                return False
    except OSError:
        return False  # An unreadable folder proves nothing; keep the history.

    def change(saved):
        screen = saved.get('screen')
        if isinstance(screen, dict) and screen.get('Screen recorder') == stamp:
            del screen['Screen recorder']
            if not screen:
                del saved['screen']
            return True
        return False
    return update_json(HISTORY, change)


def file_override(app):
    data = Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local/share'))
    return data / 'flatpak/overrides' / app


def restore_context(app, key, original):
    path = file_override(app)
    parser = configparser.ConfigParser(interpolation=None)
    parser.optionxform = str
    if path.is_file():
        parser.read(path)
    if 'Context' in parser:
        parser.remove_option('Context', key)
        if original:
            parser['Context'][key] = original
    stream = io.StringIO()
    parser.write(stream, space_around_delimiters=False)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
    with temporary.open('w') as output:
        output.write(stream.getvalue())
        output.flush()
        os.fsync(output.fileno())
    temporary.replace(path)


def permission_key(category):
    return ('location', 'location') if category == 'location' else ('devices', category)


def remember_master_choice(saved, app, category):
    before = saved.setdefault('masterBefore', {}).setdefault(category, {})
    if app in before:
        return
    table, obj = permission_key(category)
    row = next((row for row in permissions() if row['app'] == app and row['table'] == table and row['object'] == obj), None)
    context = configparser.ConfigParser(interpolation=None)
    context.read(file_override(app))
    key = 'devices' if category == 'camera' else 'sockets'
    before[app] = dict(permission=row['permission'] if row else None,
                       context=context.get('Context', key, fallback=''),
                       appChoice=saved.get('apps', {}).get(app, {}).get(category))


def set_permission(app, category, enabled, master_change=False):
    if category not in CATEGORIES:
        raise ValueError('Choose a listed permission.')
    if app.startswith('native:'):
        if app not in native.desktop_apps():
            raise ValueError('Choose an installed desktop app.')
        def change(saved):
            if saved.get('master', {}).get(category) is False and not master_change:
                raise ValueError('Turn on access for all apps first. Your app choices will come back.')
            saved.setdefault('apps', {}).setdefault(native.permission_identity(app), {})[category] = enabled
        # Install launch mediation before saving a denial. Failure must not be labeled as a block.
        native.sync_entries()
        update_json(PREFS, change)
        name = native.desktop_apps()[app]['name']
        return dict(ok=True, message=f"{name} can {'use' if enabled else 'no longer use'} the {category}{' again' if enabled else ''}. Close and reopen {name} for this to apply.")
    if not APP.fullmatch(app) or app not in apps():
        raise ValueError('Choose an installed desktop app and a listed permission.')
    PREFS.parent.mkdir(parents=True, exist_ok=True)
    with PREFS.with_suffix('.lock').open('w') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        saved = read_json(PREFS)
        if saved.get('master', {}).get(category) is False and not master_change:
            raise ValueError('Turn on access for all apps first. Your app choices will come back.')
        if master_change:
            remember_master_choice(saved, app, category)
            # Preserve restoration information even if a later service command fails partway through.
            write_json(PREFS, saved)
        if category == 'screen':
            native.sync_entries()
        if category in ('camera', 'microphone'):
            run('flatpak', 'permission-set', 'devices', category, app, 'yes' if enabled else 'no')
            if category == 'camera':
                if enabled:
                    if app in saved.get('devicesBefore', {}):
                        restore_context(app, 'devices', saved['devicesBefore'][app])
                else:
                    parser = configparser.ConfigParser(interpolation=None)
                    parser.read(file_override(app))
                    original = parser.get('Context', 'devices', fallback='')
                    run('flatpak', 'override', '--user', '--nodevice=all', app)
                    saved.setdefault('devicesBefore', {}).setdefault(app, original)
            if category == 'microphone':
                run('flatpak', 'override', '--user', '--socket=pulseaudio' if enabled else '--nosocket=pulseaudio', app)
        elif category == 'location':
            run('flatpak', 'permission-set', 'location', 'location', app, 'EXACT' if enabled else 'NONE', '0')
        elif category == 'screen':
            for row in permissions():
                if row['app'] == app and row['table'] in ('screencast', 'remote-desktop'):
                    run('flatpak', 'permission-remove', row['table'], row['object'], app)
        elif category == 'files':
            if enabled:
                restore_context(app, 'filesystems', saved['filesBefore'][app]) if app in saved.get('filesBefore', {}) else None
            else:
                parser = configparser.ConfigParser(interpolation=None)
                parser.read(file_override(app))
                original = parser.get('Context', 'filesystems', fallback='')
                for row in permissions():
                    if row['app'] == app and row['table'] == 'documents':
                        run('flatpak', 'permission-set', 'documents', row['object'], app)
                run('flatpak', 'override', '--user', '--nofilesystem=host:reset', app)
                saved.setdefault('filesBefore', {}).setdefault(app, original)
        saved.setdefault('apps', {}).setdefault(app, {})[category] = enabled
        write_json(PREFS, saved)
    message = ('Screen sharing choice saved. Close and reopen the app; a current share continues until you stop it.' if category == 'screen'
               else 'File grants removed. Close and reopen the app; it can ask for files you choose again.' if category == 'files' and not enabled
               else 'Permission saved. Close and reopen the app if it is open.')
    return dict(ok=True, message=message)


def master(category, enabled):
    if category not in ('camera', 'microphone', 'location', 'screen'):
        raise ValueError('Choose Camera, Microphone, Location or Screen.')
    native.sync_entries()
    if category == 'screen':
        update_json(PREFS, lambda saved: saved.setdefault('master', {}).update({category: enabled}))
        return dict(ok=True, message='Your earlier app choices are back. Close and reopen apps for this to apply.' if enabled
                    else 'Blocked for all apps. Close and reopen apps for this to apply.')
    installed = apps()
    failed = []
    if not enabled:
        for app in installed:
            try:
                set_permission(app, category, False, master_change=True)
            except ValueError:
                failed.append(app)
        if failed:
            raise ValueError("Some app permissions couldn't be blocked. Check the individual app states before relying on this control.")
        update_json(PREFS, lambda saved: saved.setdefault('master', {}).update({category: False}))
    else:
        PREFS.parent.mkdir(parents=True, exist_ok=True)
        with PREFS.with_suffix('.lock').open('w') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            saved = read_json(PREFS)
            previous = saved.get('masterBefore', {}).get(category, {})
            table, obj = permission_key(category)
            # Publish the removal of the block before the first grant. The portal store cannot restore a
            # group atomically; a failed later command must never leave allowed apps labeled as blocked.
            # Keep the original choices until every restoration succeeds, so retry is lossless.
            saved.setdefault('master', {})[category] = True
            write_json(PREFS, saved)
            for app, choice in previous.items():
                if app not in installed:
                    continue
                try:
                    if choice['permission'] is None:
                        if any(row['app'] == app and row['table'] == table and row['object'] == obj for row in permissions()):
                            run('flatpak', 'permission-remove', table, obj, app)
                    else:
                        run('flatpak', 'permission-set', table, obj, app, *choice['permission'].split(','))
                    if category in ('camera', 'microphone'):
                        restore_context(app, 'devices' if category == 'camera' else 'sockets', choice['context'])
                    # The launch broker and portal must agree, including during a partial
                    # restore. None means there was no saved per-app choice before blocking.
                    # Old snapshots predate appChoice; recover their original portal policy.
                    original = choice.get('appChoice',
                                          False if choice['permission'] in ('no', 'NONE', 'NONE,0') else None)
                    app_choices = saved.setdefault('apps', {}).setdefault(app, {})
                    if original is None:
                        app_choices.pop(category, None)
                    else:
                        app_choices[category] = original
                    write_json(PREFS, saved)
                except (OSError, ValueError):
                    failed.append(app)
            if failed:
                raise ValueError("Some previous app choices couldn't be restored. Restored apps have access; the master block is off. Try turning access on again to finish.")
            saved.setdefault('master', {})[category] = True
            saved.setdefault('masterBefore', {}).pop(category, None)
            write_json(PREFS, saved)
    return dict(ok=True, message='Your earlier app choices are back. Close and reopen apps for this to apply.' if enabled
                else 'Blocked for all apps. Close and reopen apps for this to apply.')


def enforce_masters(known):
    saved = read_json(PREFS)
    installed = apps()
    native.sync_entries()
    for category, enabled in saved.get('master', {}).items():
        if enabled is False and category in ('camera', 'microphone', 'location'):
            for app in set(installed) - known:
                set_permission(app, category, False, master_change=True)
    return set(installed)


def watch_installs():
    import ctypes
    import select
    library = ctypes.CDLL(None, use_errno=True)
    fd = library.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC)
    if fd < 0:
        raise OSError("Permission monitoring couldn't start.")
    known = set()
    roots = (Path('/var/lib/flatpak/app'), Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local/share')) / 'flatpak/app',
             *native.application_dirs())
    watched = set()
    due = True                       # the first look, then only after an install event or a newly watched folder
    try:
        while True:
            for root in roots:
                parent = root if root.is_dir() else root.parent
                if parent.is_dir() and parent not in watched:
                    if library.inotify_add_watch(fd, os.fsencode(parent), 0x100 | 0x80 | 0x400 | 0x8) >= 0:
                        watched.add(parent)
                        due = True
            if due:
                try:
                    known = enforce_masters(known)
                    due = False
                except ValueError:
                    pass  # Flatpak can be updating its installation; retry after the next event.
            # a look lists every app (Flatpak included): never on a clock. The 30 s wake only looks for folders that
            # didn't exist yet (a first Flatpak install makes them), and for a look that failed
            if select.select([fd], [], [], 30)[0]:
                os.read(fd, 65536)
                due = True
    finally:
        os.close(fd)


def status():
    installed, rows, saved = apps(), permissions(), read_json(PREFS)
    out, shown = [], set()
    for app, entry in native.desktop_apps().items():
        if entry['flatpak'] or not native.listed_app(entry):
            continue
        identity = native.permission_identity(app)
        if identity in shown:
            continue
        shown.add(identity)
        choices = native.effective(app)
        out.append(dict(id=app, name='LibreOffice' if identity == 'native:libreoffice.desktop' else entry['name'], icon=entry.get('icon', ''), native=True, permissions={key: dict(allowed=choices[key], state='Allowed' if choices[key] else 'Blocked') for key in CATEGORIES}))
    for app, name in installed.items():
        controls = {}
        for category in CATEGORIES:
            table, obj = ('devices', category) if category in ('camera', 'microphone') else ('location', 'location')
            row = next((r for r in rows if r['app'] == app and r['table'] == table and r['object'] == obj), None)
            permission = row['permission'] if row else ''
            controls[category] = dict(allowed=native.effective(app)[category] if category == 'screen' else permission not in ('no', 'NONE,0', 'NONE') if category in ('camera', 'microphone', 'location') else True,
                                      state='Asks first' if not permission else 'Blocked' if permission in ('no', 'NONE,0', 'NONE') else 'Allowed')
            if category == 'files':
                controls[category] = dict(allowed=native.effective(app)[category],
                                          state='Allowed' if native.effective(app)[category] else 'Blocked')
            if category == 'screen':
                controls[category]['state'] = 'Allowed' if controls[category]['allowed'] else 'Blocked'
        out.append(dict(id=app, name=name.removesuffix(" (Launcher)"), icon=app, permissions=controls))
    recent = history()
    requested = read_json(REQUESTS)
    discovered = {category: {r['app'] for r in rows if r['object'] == category and r['table'] in ('devices', 'location')} for category in CATEGORIES}
    for app in out:
        if app.get('native'):
            identity = native.permission_identity(app['id'])
            if saved.get('apps', {}).get(identity):
                for category in saved['apps'][identity]:
                    if category in discovered:
                        discovered[category].add(app['id'])
    if any(app not in requested.get(category, {}) for category, ids in discovered.items() for app in ids):
        def record_requests(value):
            for category, ids in discovered.items():
                known = value.setdefault(category, {})
                for app in ids:
                    known.setdefault(app, int(time.time()))
                while len(known) > 200:
                    del known[min(known, key=known.get)]
        update_json(REQUESTS, record_requests)
        requested = read_json(REQUESTS)
    # Suite rows inherit use recorded under any of their launcher names.
    for app in out:
        if app.get('native'):
            names = {entry['name'] for ident, entry in native.desktop_apps().items() if native.permission_identity(ident) == native.permission_identity(app['id'])}
            for uses in recent.values():
                stamp = max((uses.get(name, 0) for name in names), default=0)
                if stamp:
                    uses[app['name']] = max(uses.get(app['name'], 0), stamp)
    return dict(ok=True, apps=sorted(out, key=lambda a: a['name'].casefold()), history=recent, requests=requested, master=saved.get('master', {}),
                scope='Choose what each app may use. A change applies the next time the app opens. Apps that are already open, and commands you run in a terminal, are not affected.')


def main(args):
    if args in (['-h'], ['--help'], ['help']):
        print(__doc__)
        return 0
    try:
        if args == ['status']:
            result = status()
        elif len(args) == 4 and args[0] == 'set' and args[3] in ('on', 'off'):
            result = set_permission(args[1], args[2], args[3] == 'on')
        elif len(args) == 3 and args[0] == 'master' and args[2] in ('on', 'off'):
            result = master(args[1], args[2] == 'on')
        elif len(args) == 2 and args[0] == 'restore':
            for category in CATEGORIES:
                set_permission(args[1], category, True)
            name = native.desktop_apps()[args[1]]['name'] if args[1].startswith('native:') else apps()[args[1]]
            result = dict(ok=True, message=f'{name} can use everything again. Close and reopen {name} for this to apply.')
        elif args == ['watch']:
            watch_installs()
            return 0
        elif args == ['clear-history']:
            clear_history()
            result = dict(ok=True, message='Recent-use history cleared.')
        else:
            print(__doc__, file=sys.stderr)
            return 2
        print(json.dumps(result))
        return 0
    except (OSError, ValueError) as error:
        print(json.dumps(dict(ok=False, errors=str(error))))
        return 1


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