#!/usr/bin/env python3
# summary: Manage the isolated security practice workspace.
"""Security lab: a separate workspace for tools and isolated practice targets.

Usage: starchaser seclab catalog|status|hardware|folder|log|terminal
       starchaser seclab install|add [GROUP ...] [--capture] [--gpu] [--lan]
       starchaser seclab remove-group GROUP ...
       starchaser seclab update|uninstall
       starchaser seclab tool TOOL
       starchaser seclab exec COMMAND [ARG ...]
       starchaser seclab target-start ID --accept-license
       starchaser seclab target-stop|target-remove ID
       starchaser seclab evidence FILE
       starchaser seclab guide web|network|file [ADDRESS]
       starchaser seclab prepare-goal web|network|file [OPTIONS]
       starchaser seclab capture-enable TOOL [--accept-scope]
       starchaser seclab save-report LAB_FILE
       starchaser seclab make-pdf LAB_REPORT.md
       starchaser seclab start ACTION [ARG ...]
       starchaser seclab permissions [--capture] [--gpu] [--lan] [--usb DEVICE]
       starchaser seclab welcome

start runs a change in the background; status reports progress and the result after Settings closes.
welcome opens the learning setup page for scope acknowledgement before any download.
Install requires --accept-scope after reading the permission statement in Settings.
Use --password-each-session (default) or --remember-sessions with install or permissions.
folder opens the reports folder after setup in Settings > Security > Security lab.
Update closes lab programs and resets downloaded practice targets; reports and evidence are kept.
Removing tool groups closes open lab programs. Target controls keep tool sessions open.
Removing the lab keeps your reports, evidence, and separate home. The shared container engine stays installed.
"""
import argparse
import ipaddress
import fcntl
import grp
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import command_usage_error, safe_streams
safe_streams()

ADMIN = '/usr/local/lib/starchaser/starchaser-seclab-admin'
SESSION = '/usr/local/lib/starchaser/starchaser-seclab-session'
ROOT = Path('/var/lib/starchaser/security-lab')
STATE = Path(os.environ.get('XDG_STATE_HOME', str(Path.home() / '.local/state'))) / 'starchaser/seclab'
APPS = Path(os.environ.get('XDG_DATA_HOME', str(Path.home() / '.local/share'))) / 'applications'
CATALOG = Path(__file__).resolve().parent.parent / 'data/security-lab.json'
if not CATALOG.exists():
    CATALOG = Path('/usr/local/share/starchaser/security-lab.json')


class ArgumentError(ValueError):
    """An invalid command argument, separate from a failed lab operation."""


def read_json(path, default):
    try:
        data = json.loads(path.read_text())
        return data if isinstance(data, type(default)) else default
    except (OSError, ValueError):
        return default


def write_json(path, value):
    temp = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
    with temp.open('w') as stream:
        json.dump(value, stream)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temp, path)


def process_start(pid):
    try:
        return Path(f'/proc/{int(pid)}/stat').read_text().rsplit(')', 1)[1].split()[19]
    except (OSError, ValueError, IndexError):
        return ''


def same_process(pid, start, boot=None):
    if boot and boot != Path('/proc/sys/kernel/random/boot_id').read_text().strip():
        return False
    return bool(pid and start and process_start(pid) == start)


def session_helper():
    return SESSION if status().get('passwordEachSession', True) else ADMIN


def save_report(source, pdf):
    path = Path(source)
    name = path.stem + '.pdf' if pdf else (path.stem + '-copy' + path.suffix if path.parts[:2] == ('/', 'shared') else path.name)
    if not name or name in ('.', '..') or '/' in name:
        raise ArgumentError('Choose a file in the lab.')
    shared = ROOT / 'workspace/shared'
    destination = shared / name
    if destination.exists() or destination.is_symlink():
        raise RuntimeError('A report with that name already exists. Rename the source or the saved report first.')
    fd, temporary = tempfile.mkstemp(prefix='.report-', dir=shared)
    try:
        with os.fdopen(fd, 'wb') as output, tempfile.TemporaryFile('w+') as error:
            result = subprocess.run(['pkexec', session_helper(), 'report-pdf' if pdf else 'report-copy', '--source', source],
                                    stdout=output, stderr=error, check=False)
            if result.returncode:
                error.seek(0)
                raise RuntimeError(auth_message(error.read()).strip() or "The report couldn't be exported. Install Reporting to make PDFs.")
            output.flush()
            os.fsync(output.fileno())
        try:
            os.link(temporary, destination)
        except FileExistsError as exc:
            raise RuntimeError('A report with that name already exists.') from exc
    finally:
        os.unlink(temporary)
    return destination


def current_access(value, capture=None):
    words = []
    for key in ('lan', 'capture', 'gpu'):
        if (capture if key == 'capture' and capture is not None else value.get(key)):
            words.append('--' + key)
    if value.get('usb'):
        words += ['--usb', value['usb']]
    return words


def status():
    value = read_json(ROOT / 'state.json', {'installed': False, 'groups': [], 'targets': {}})
    try:
        value['admin'] = grp.getgrnam('wheel').gr_gid in os.getgroups()
    except KeyError:
        value['admin'] = False
    value['captureRequest'] = read_json(STATE / 'capture-request.json', {}).get('tool', '')
    if not isinstance(value.get('groups'), list) or not isinstance(value.get('targets'), dict):
        value.update(installed=False, ready=False, groups=[], targets={}, message='The lab state file is damaged. Ask an administrator to restore state.json from a backup. No tools can open until it is repaired.')
    value['owned'] = value.get('uid', os.getuid()) == os.getuid()
    job = read_json(STATE / 'job.json', {})
    pid = job.get('pid', 0)
    job_busy = bool(job.get('running') and same_process(pid, job.get('processStart'), job.get('boot')))
    worker_pid = value.get('workerPid', 0)
    worker_busy = same_process(worker_pid, value.get('workerStart'), value.get('boot'))
    value['busy'] = job_busy or worker_busy
    if worker_pid and not worker_busy:
        value['message'] = 'Setup was interrupted. Retry the change, or remove the unfinished lab.'
    if job.get('running') and not job_busy:
        job.update(running=False, ok=False, error='Setup was interrupted. Retry the change, or remove the unfinished lab.')
    value['job'] = job
    if value.get('boot') != Path('/proc/sys/kernel/random/boot_id').read_text().strip():
        for target in value.get('targets', {}).values():
            target['running'] = False
    for target in value.get('targets', {}).values():
        if target.get('running'):
            try:
                start = Path(f'/proc/{target.get("pid", 0)}/stat').read_text().split(') ', 1)[1].split()[19]
                target['running'] = start == target.get('processStart')
            except (OSError, IndexError):
                target['running'] = False
    value['freeMB'] = shutil.disk_usage(ROOT if ROOT.exists() else Path.home()).free // 1000000
    activity = ROOT / 'activity.jsonl'
    try:
        value['activity'] = [json.loads(row) for row in activity.read_text().splitlines()[-30:]]
    except (OSError, ValueError):
        value['activity'] = []
    value['log'] = str(STATE / 'install.log')
    value['hasLog'] = (STATE / 'install.log').is_file()
    return value


def hardware():
    adapters = []
    for interface in Path('/sys/class/net').glob('*'):
        if not (interface / 'wireless').exists():
            continue
        for parent in (interface / 'device').resolve().parents:
            if (parent / 'busnum').exists() and (parent / 'devnum').exists():
                bus, device = int((parent / 'busnum').read_text()), int((parent / 'devnum').read_text())
                adapters.append({'name': interface.name, 'device': f'/dev/bus/usb/{bus:03}/{device:03}'})
                break
    current = status()
    selected = current.get('usb')
    if (current.get('owned') and selected and current.get('usbPhy')
            and selected not in {adapter['device'] for adapter in adapters}):
        adapters.append({'name': current.get('usbInterface', 'USB Wi-Fi adapter') + ' (assigned to lab)', 'device': selected})
    return {'gpu': bool(list(Path('/dev/dri').glob('renderD*')) or list(Path('/dev').glob('nvidia[0-9]*'))), 'adapters': adapters}


def link_workspace():
    path = Path.home() / 'SecurityLab'
    if not path.exists() and not path.is_symlink():
        path.symlink_to(ROOT / 'workspace', target_is_directory=True)
    shared = ROOT / 'workspace/shared'
    report = shared / 'report-template.md'
    if shared.exists() and not report.exists():
        # Written as the desktop user: existing reports are never overwritten or written as root.
        with report.open('x') as stream:
            stream.write('# Security assessment\n\n## Permission and scope\n\nOwner: \nAuthorized targets: \nTest dates: \n'
                         '\n## Findings\n\n### Finding title\n\nSeverity: \nAffected system: \nEvidence: \n'
                         'Steps to reproduce: \nRecommended fix: \n\n## Retest\n\nResult: \n')


def launchers():
    value = status()
    APPS.mkdir(parents=True, exist_ok=True)
    for path in APPS.glob('starchaser-seclab-*.desktop'):
        path.unlink()
    if not value.get('installed') or not value.get('owned'):
        return
    data = json.loads(CATALOG.read_text())
    for group in data['groups']:
        if group['id'] not in value['groups']:
            continue
        for tool in group['tools']:
            path = APPS / ('starchaser-seclab-' + tool['id'] + '.desktop')
            path.write_text('[Desktop Entry]\nType=Application\nName=' + tool['name'] + ' · Security lab\n'
                            'Comment=' + tool['description'] + (' Opens a window.' if tool['gui'] else ' Opens a terminal with instructions.') + '\nExec=starchaser seclab tool ' + tool['id'] + '\n'
                            'Icon=security-high\nTerminal=false\nCategories=Security;X-Starchaser-SecurityLab;\n'
                            'Keywords=Security lab;assessment;\n')
    if shutil.which('update-desktop-database'):
        subprocess.run(['update-desktop-database', str(APPS)], check=False, capture_output=True)


def check_words(action, words):
    # Catch typos before the password prompt; the root helper still validates too.
    known = {g['id'] for g in json.loads(CATALOG.read_text())['groups']}
    groups = action in ('install', 'add', 'remove-group')
    items = iter(words)
    for word in items:
        if word == '--usb' and action in ('install', 'add', 'permissions'):
            value = next(items, '')
            if not value or value.startswith('-'):
                raise ArgumentError('--usb needs a device name.')
        elif word in ('--capture', '--gpu', '--lan', '--accept-scope', '--remember-sessions', '--password-each-session') and action in ('install', 'add', 'permissions'):
            continue
        elif word.startswith('-'):
            raise ArgumentError(f'Unknown option {word!r} for {action}.')
        elif not groups or word not in known:
            raise ArgumentError(f'Unknown group {word!r}; use catalog to see group IDs.')
    if action == 'remove-group' and not words:
        raise ArgumentError('Missing group to remove.')


def prepare_goal(words):
    parser = argparse.ArgumentParser(prog="starchaser seclab", add_help=False, exit_on_error=False)
    parser.add_argument('goal', nargs='?', choices=['web', 'network', 'file'])
    parser.add_argument('--accept-license', action='store_true')
    parser.add_argument('--address', default='')
    parser.add_argument('--evidence', default='')
    for flag in ('accept-scope', 'capture', 'gpu', 'lan', 'password-each-session', 'remember-sessions'):
        parser.add_argument('--' + flag, action='store_true')
    parser.add_argument('--usb', default='')
    try:
        args, unknown = parser.parse_known_args(words)
    except argparse.ArgumentError as exc:
        raise ArgumentError(str(exc)) from exc
    if unknown:
        raise ArgumentError('Unknown learning option: ' + unknown[0])
    if not args.goal:
        raise ArgumentError('Choose a learning goal: web, network, or file.')
    if args.goal == 'web' and not args.accept_license:
        raise ArgumentError('Read and accept the Juice Shop license before starting the lesson.')
    if args.goal == 'network':
        if not args.lan:
            raise ArgumentError('Turn on real network access before scanning your own network.')
        try:
            ipaddress.ip_network(args.address, strict=False)
        except ValueError as exc:
            raise ArgumentError('Enter a numeric IP address or network, for example 192.168.1.10.') from exc
    groups = {'web': ['network', 'web', 'reporting'], 'network': ['network', 'reporting'],
              'file': ['forensics', 'reporting']}[args.goal]
    options = [word for flag in ('accept-scope', 'capture', 'gpu', 'lan', 'password-each-session', 'remember-sessions')
               if getattr(args, flag.replace('-', '_')) for word in ['--' + flag]]
    if args.usb:
        options += ['--usb', args.usb]
    return args, ['install', *groups, *options]


def admin_args(args):
    action, *words = args
    if action == 'prepare-goal':
        goal, install_args = prepare_goal(words)
        command = admin_args(install_args)
        command[1] = 'prepare-goal'
        command += ['--guide', goal.goal, '--address', goal.address]
        if goal.accept_license:
            command.append('--accept-license')
        return command
    if action == 'capture-enable':
        if not words or any(w != '--accept-scope' for w in words[1:]) or not any(words[0] == t['id'] for g in json.loads(CATALOG.read_text())['groups'] for t in g['tools']):
            raise ArgumentError('Choose one installed capture tool.')
        return admin_args(['permissions', *current_access(status(), capture=True), *words[1:]])
    allowed = {'install', 'add', 'update', 'remove-group', 'uninstall', 'target-start', 'target-stop', 'target-remove', 'exec', 'permissions'}
    if action not in allowed:
        raise ArgumentError('Unknown change. Use --help for available commands.')
    if action in ('install', 'add', 'remove-group', 'permissions'):
        check_words(action, words)
    if action in ('uninstall', 'update') and words:
        raise ArgumentError(action + ' takes no extra arguments.')
    if action.startswith('target-'):
        if not words:
            raise ArgumentError('Missing practice target ID.')
        if words[0].startswith('-') or (words[1:] and not (action == 'target-start' and words[1:] == ['--accept-license'])):
            raise ArgumentError('Choose one practice target ID; only target-start accepts --accept-license.')
        words = ['--target', words[0], *words[1:]]
    if action in ('install', 'add', 'permissions', 'update') and os.environ.get('WAYLAND_DISPLAY'):
        words += ['--display', os.environ['WAYLAND_DISPLAY']]
    if action in ('install', 'add', 'permissions', 'update') and os.environ.get('DISPLAY') and os.environ.get('XAUTHORITY'):
        words += ['--xdisplay', os.environ['DISPLAY'], '--xauthority', os.environ['XAUTHORITY']]
    return [ADMIN, action, *words]


def auth_message(text):
    # Without a password window, polkit prints terminal jargon; say what to do instead.
    if 'textual authentication agent' in text or '/dev/tty' in text:
        return 'No password window opened, so the change did not start. Sign out and back in, then try again.'
    return text


def worker(args):
    goal = prepare_goal(args[1:])[0] if args[0] == 'prepare-goal' else None
    if args[0] == 'capture-enable':
        admin_args(args)
        result = worker(['permissions', *current_access(status(), capture=True), *args[2:]])
        if result == 0:
            (STATE / 'capture-request.json').unlink(missing_ok=True)
            return main(['tool', args[1]])
        return result
    command = admin_args(args)
    STATE.mkdir(parents=True, exist_ok=True)
    with (STATE / 'job.lock').open('w') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as exc:
            raise RuntimeError('Another Security lab change is running.') from exc
        job = {'pid': os.getpid(), 'processStart': process_start(os.getpid()),
               'boot': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'running': True, 'action': args[0]}
        write_json(STATE / 'job.json', job)
        with (STATE / 'install.log').open('w') as log:
            result = subprocess.run(['pkexec', *command], stdout=log, stderr=subprocess.STDOUT, check=False)
        job.update(running=False, ok=result.returncode == 0)
        if result.returncode:
            job['error'] = ('The password prompt was canceled.' if result.returncode == 126 else
                            auth_message((STATE / 'install.log').read_text(errors='replace')[-2500:])
                            or 'The lab change could not start.')
        try:
            if status().get('owned'):
                link_workspace()
                launchers()
            if job['ok'] and goal:
                if goal.evidence:
                    main(['evidence', goal.evidence])
                main(['guide', goal.goal] + ([goal.address] if goal.address else []))
        except (OSError, ValueError, RuntimeError) as exc:
            job.update(ok=False, error=('The lesson could not open: ' if goal else
                                       'The lab changed, but its menu or shared folder could not be set up: ') + str(exc))
        write_json(STATE / 'job.json', job)
        if shutil.which('notify-send'):
            subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", '-a', 'Security lab', 'Security lab is ready' if job['ok'] else 'Security lab needs attention',
                            'See Settings > Security > Security lab for the result.'], check=False)
        print(json.dumps(job))
        return 0 if job['ok'] else 1


def seclab_usage_error(args, message=None):
    commands = {
        **{name: (name, (), ()) for name in
           ("catalog", "status", "hardware", "folder", "log", "terminal", "update", "uninstall", "welcome")},
        **{name: (f"{name} [group ...] [--capture] [--gpu] [--lan]", (), ()) for name in ("install", "add")},
        "remove-group": ("remove-group <group> [group ...]", ("group",), ()),
        "permissions": ("permissions [--capture] [--gpu] [--lan] [--usb <device>]", (), ()),
        "tool": ("tool <tool-id>", ("tool ID (see catalog)",), ()),
        "exec": ("exec <command> [arg ...]", ("command to run",), ()),
        "evidence": ("evidence <file>", ("file",), ()),
        "activity": ("activity", (), ()),
        "capture-cancel": ("capture-cancel", (), ()),
        "open-report": ("open-report <file>", ("file",), ()),
        "save-report": ("save-report <lab-file>", ("lab file",), ()),
        "make-pdf": ("make-pdf <lab-report.md>", ("lab report",), ()),
        "guide": ("guide <web|network|file> [address]", ("goal",), ("web", "network", "file")),
        "prepare-goal": ("prepare-goal <web|network|file> [--accept-license] [--lan --address <address>] [--evidence <file>] [--accept-scope]", ("goal",), ("web", "network", "file")),
        "capture-enable": ("capture-enable <tool-id> [--accept-scope]", ("tool ID (see catalog)",), ()),
        "target-start": ("target-start <id> --accept-license", ("practice target ID", "--accept-license"), ()),
        **{name: (f"{name} <id>", ("practice target ID",), ()) for name in ("target-stop", "target-remove")},
        "start": ("start <action> [arg ...]", ("action",),
                  ("install", "add", "update", "remove-group", "uninstall", "target-start", "target-stop", "target-remove", "exec", "permissions", "capture-enable", "prepare-goal")),
    }
    if args[:1] in (["start"], ["_worker"]) and len(args) > 1:
        action = args[1]
        if action in commands["start"][2]:
            syntax, required, choices = commands[action]
            return command_usage_error("starchaser seclab", args[1:],
                                       {action: (args[0] + " " + syntax, required, choices)}, message)
        message = f"unknown change {action!r}"
        args = ["start", *args[1:]]
    return command_usage_error("starchaser seclab", args, commands, message)


def main(args):
    if not args:                    # a missing command is an error like every other tool's, never a help page
        return seclab_usage_error(args)
    if args[0] in ('-h', '--help', 'help'):
        print(__doc__)
        return 0
    action, *words = args
    if action == 'exec' and words and words[0] in ('-h', '--help', 'help'):
        # the command's own help flags are passed through (below), but with no command yet this asks for ours
        print(__doc__)
        return 0
    # exec passes its arguments to another program, including that program's help flags.
    change = words[0] if action in ('start', '_worker') and words else action
    if change != 'exec' and any(word in ('-h', '--help') for word in words):
        print(__doc__)
        return 0
    if action == 'catalog' and not words:
        print(CATALOG.read_text())
    elif action == 'status' and not words:
        print(json.dumps(status()))
    elif action == 'hardware' and not words:
        print(json.dumps(hardware()))
    elif action == 'capture-cancel' and not words:
        (STATE / 'capture-request.json').unlink(missing_ok=True)
    elif action == 'open-report' and len(words) == 1:
        path = Path(words[0]).resolve(strict=True)
        shared = (ROOT / 'workspace/shared').resolve(strict=True)
        if not path.is_relative_to(shared) or not path.is_file() or path.suffix.lower() not in ('.md', '.txt', '.pdf', '.csv', '.json', '.log'):
            raise ArgumentError('Choose a text or PDF report in the Reports folder.')
        subprocess.Popen(['xdg-open', str(path)], start_new_session=True)
    elif action == 'activity' and not words:
        path = ROOT / 'activity.jsonl'
        if not path.is_file():
            raise RuntimeError('There is no lab activity yet.')
        subprocess.Popen(['xdg-open', str(path)], start_new_session=True)
    elif action in ('folder', 'log') and not words:
        path = ROOT / 'workspace/shared' if action == 'folder' else STATE / 'install.log'
        if not (path.is_dir() if action == 'folder' else path.is_file()):
            if action == 'log' and not path.exists() and not path.is_symlink():
                print('There is no setup log yet.')
                return 0
            if action == 'folder':
                if status().get('installed'):
                    raise RuntimeError('The reports folder is missing. Open Settings > Security > Security lab to check the lab setup.')
                raise RuntimeError('Set up Security lab in Settings > Security > Security lab to create the reports folder.')
            raise RuntimeError('There is no setup log yet.')
        error = "The reports folder couldn't be opened." if action == 'folder' else "The setup log couldn't be opened."
        try:
            viewer = subprocess.Popen(['xdg-open', str(path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                                      start_new_session=True)
        except OSError as exc:
            raise RuntimeError(error) from exc
        try:
            failed = viewer.wait(timeout=2) != 0
        except subprocess.TimeoutExpired:
            failed = False  # still running: the viewer is open, do not wait for it to close
        if failed:
            raise RuntimeError(error)
    elif action == 'evidence' and len(words) == 1:
        try:
            source = Path(words[0]).expanduser().resolve(strict=True)
        except FileNotFoundError as exc:
            raise ArgumentError("That file wasn't found. It may have been moved or deleted.") from exc
        if not source.is_file():
            raise ArgumentError('Choose a disk image or another regular file.')
        destination = ROOT / 'workspace/evidence' / source.name
        try:
            with source.open('rb') as src, destination.open('xb') as dst:
                shutil.copyfileobj(src, dst)
        except FileExistsError as exc:
            raise RuntimeError('A file with that name is already in the evidence folder.') from exc
        except OSError as exc:
            if not destination.parent.is_dir() and not status().get('installed'):
                raise RuntimeError('Set up Security lab in Settings > Security > Security lab to create the reports folder.') from exc
            raise RuntimeError("That file couldn't be copied into the evidence folder.") from exc
        print(json.dumps({'ok': True, 'message': 'A copy is available read-only at /evidence/' + source.name}))
    elif action in ('save-report', 'make-pdf') and len(words) == 1:
        destination = save_report(words[0], action == 'make-pdf')
        print('Saved to Reports: ' + str(destination))
    elif action in ('terminal', 'tool', 'guide'):
        command = [session_helper(), 'exec']
        gui = False
        if action == 'tool':
            if len(words) != 1:
                raise ArgumentError('tool needs one tool ID; use catalog to see tool IDs.')
            data = json.loads(CATALOG.read_text())
            tool = next((t for g in data['groups'] for t in g['tools'] if t['id'] == words[0]), None)
            if not tool:
                raise ArgumentError(f'Unknown tool {words[0]!r}; use catalog to see tool IDs.')
            value = status()
            capture_tools = {'wireshark', 'tcpdump', 'arp-scan', 'aircrack-ng', 'kismet', 'hcx', 'wifite', 'iw'}
            if tool['id'] in capture_tools and not value.get('capture'):
                STATE.mkdir(parents=True, exist_ok=True)
                write_json(STATE / 'capture-request.json', {'tool': tool['id']})
                subprocess.Popen(['starchaser', 'settings', 'seclab'], start_new_session=True)
                return 0
            gui = tool['gui']
            command += ['--tool', tool['id']]
        elif action == 'guide':
            if not words or words[0] not in ('web', 'network', 'file') or len(words) > 2:
                raise ArgumentError('Choose web, network, or file, followed by an authorized address for network scans.')
            command += ['--guide', words[0], '--address', words[1] if len(words) > 1 else '']
        elif words:
            raise ArgumentError('terminal takes no extra arguments.')
        if gui:
            # Keep the requesting process alive while the password prompt and app run.
            # Desktop launch scopes may end their children when this process exits.
            return main(['_run', *command])
        else:
            command += ['--prompt']
            # the change runs inside the lab's terminal through _run: a password window that couldn't open gets
            # the plain sentence there instead of pkexec's jargon (the same words as `exec`)
            command = ['starchaser', 'terminal', '--title', (tool['name'] + ' · Security lab terminal' if action == 'tool' else (words[0].capitalize() + ' lesson · Security lab terminal' if action == 'guide' else 'Security lab terminal')), sys.executable,
                       str(Path(__file__).resolve()), '_run', *command]
        subprocess.Popen(command, start_new_session=True)
    elif action == '_run' and words:
        with tempfile.TemporaryFile('w+') as err:
            result = subprocess.run(['pkexec', *words], check=False, stderr=err)
            err.seek(0)
            text = err.read()
        problem = auth_message(text)
        if problem != text:
            print(problem, file=sys.stderr)
            return 1
        if text:
            sys.stderr.write(text)
        return result.returncode
    elif action == 'exec' and words:
        # the command's own output passes through; a password window that couldn't open gets the plain
        # explanation instead of pkexec's jargon (the same words as `permissions`)
        with tempfile.TemporaryFile('w+') as err:
            result = subprocess.run(['pkexec', session_helper(), 'exec', '--', *words], check=False, stderr=err)
            err.seek(0)
            text = err.read()
        problem = auth_message(text)
        if problem != text:
            raise RuntimeError(problem)
        if text:
            sys.stderr.write(text)
        return result.returncode
    elif action == 'welcome' and not words:
        subprocess.Popen(['starchaser', 'settings', 'seclab'], start_new_session=True)
        return 0
    elif action == 'start' and words:
        admin_args(words)  # reject unknown actions before detaching
        STATE.mkdir(parents=True, exist_ok=True)
        if status()['busy']:
            raise RuntimeError('Another Security lab change is running.')
        with (STATE / 'worker.log').open('a') as log:
            process = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), '_worker', *words],
                                       stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
        print(json.dumps({'ok': True, 'pid': process.pid,
                          'note': 'Change started in the background. Check starchaser seclab status for the result.'}))
    elif action == '_worker' and words:
        return worker(words)
    elif action in ('install', 'add', 'update', 'remove-group', 'uninstall', 'target-start', 'target-stop', 'target-remove', 'permissions', 'capture-enable', 'prepare-goal'):
        return worker(args)
    else:
        return seclab_usage_error(args)
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main(sys.argv[1:]))
    except ArgumentError as exc:
        sys.exit(seclab_usage_error(sys.argv[1:], str(exc)))
    except OSError as exc:
        # a folder it may not write: plain words, never the raw "[Errno 13] ..." text
        print(f"starchaser seclab: couldn't save the lab's files ({exc.strerror or exc}). "
              "Check that you can write to ~/.local/share and ~/.local/state.", file=sys.stderr)
        sys.exit(1)
    except (ValueError, RuntimeError) as exc:
        print(str(exc), file=sys.stderr)
        sys.exit(1)
