#!/usr/bin/env python3
# summary: Apply this account's privacy choices when opening a desktop app.
"""Usage: starchaser app permissions desktop DESKTOP-ID | launch APP -- COMMAND [ARGUMENT ...]
       starchaser app permissions command DESKTOP-ID -- COMMAND [ARGUMENT ...] | shell APP-HINT -- SHELL-COMMAND
       starchaser app permissions menu DESKTOP-ID -- LAUNCH-JSON
       starchaser app permissions website APP -- APPIMAGE [SELECTED-FILE]

Apply this account's privacy choices when opening a desktop app.
"""
import json
import os
import shlex
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_app_privacy as privacy


def main(args):
    if args in ([], ['-h'], ['--help'], ['help']):
        print(__doc__)
        return 0
    try:
        if len(args) == 4 and args[0] == 'menu' and args[2] == '--':
            plan = json.loads(args[3])
            if not isinstance(plan, dict):
                raise ValueError('Choose an installed desktop app.')
            command = plan.get('command')
            directory = plan.get('directory', '')
            if not isinstance(command, list) or not command or not all(isinstance(word, str) for word in command) or not isinstance(directory, str):
                raise ValueError('Choose an installed desktop app.')
            app = privacy.desktop_identity(args[1], shlex.join(command))
            previous = os.getcwd()
            started = time.monotonic()
            try:
                if directory:
                    os.chdir(directory)
                if plan.get('mediated'):
                    privacy.sync_entries()
                    result = subprocess.call(command)
                else:
                    result = privacy.launch(app, command, directory=directory) if app else subprocess.call(command)
            finally:
                os.chdir(previous)
            return 0 if plan.get('timed') and time.monotonic() - started >= 3 else result
        if len(args) >= 4 and args[0] in ('shell', 'command') and args[2] == '--':
            command = ['sh', '-c', args[3]] if args[0] == 'shell' else args[3:]
            hint_command = args[3] if args[0] == 'shell' else ' '.join(command)
            app = privacy.desktop_identity(args[1], hint_command)
            return privacy.launch(app, command) if app else subprocess.call(command)
        if args and args[0] == 'desktop' and len(args) == 2:
            if '/' in args[1] or not args[1] or args[1].startswith('-'):
                raise ValueError('Choose an installed desktop app.')
            privacy.sync_entries()
            return subprocess.call(['gtk-launch', args[1]])
        if len(args) >= 4 and args[0] == 'launch' and args[2] == '--':
            return privacy.launch(args[1], args[3:])
        if len(args) in (4, 5) and args[0] == 'website' and args[2] == '--':
            return privacy.launch_website(args[1], args[3:])
        print(__doc__, file=sys.stderr)
        return 0 if args in ([], ['-h'], ['--help'], ['help']) else 2
    except (OSError, ValueError) as error:
        message = str(error)
        print('App kept closed: ' + message, file=sys.stderr)
        subprocess.run(['sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"', 'starchaser', 'notify', '-a', 'Starchaser', 'App kept closed', message], check=False)
        return 1


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