#!/usr/bin/env python3
# summary: Open the spoken recovery guide.
"""Starchaser Recovery: the same spoken, keyboard guide on the stick and disk.

usage: starchaser rescue [--install-environment BOOT --installed-root ROOT]
The guide runs as root in the independent recovery environment only.
--install-environment copies this environment to the mounted boot partition,
using the selected --installed-root for its startup signing configuration.
"""
import argparse
import getpass
import io
import tempfile
import shlex
import signal
import shutil
import importlib.machinery
import importlib.util
import json
import os
import re
import stat
import subprocess
import sys
from pathlib import Path

REPO = Path(__file__).resolve().parents[1]
for folder in (REPO / 'system/usr/local/lib/starchaser', Path('/usr/local/lib/starchaser')):
    if (folder / 'rescue.py').is_file():
        sys.path.insert(0, str(folder))
        break
import rescue


def reset_module():
    loader = importlib.machinery.SourceFileLoader('rescue_password', str(Path(__file__).resolve().with_name('starchaser-reset-password')))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    module = importlib.util.module_from_spec(spec)
    loader.exec_module(module)
    return module


SPEECH = True
UI = False
NOTES = []
REQUEST_ID = 0


def emit(data):
    print('@@' + json.dumps(data), flush=True)


def request(kind, title, rows=None):
    global REQUEST_ID
    REQUEST_ID += 1
    emit({'event': 'request', 'id': REQUEST_ID, 'kind': kind, 'title': title, 'rows': rows or [], 'notes': '\n\n'.join(NOTES)})
    NOTES.clear()
    while True:
        line = sys.stdin.readline()
        if not line:
            raise EOFError()
        try:
            reply = json.loads(line)
        except ValueError:
            continue
        if not isinstance(reply, dict) or reply.get('id') != REQUEST_ID:
            continue
        if reply.get('cancel'):
            raise EOFError()
        value = reply.get('value')
        if kind == 'choice' and (not isinstance(value, int) or isinstance(value, bool) or not -1 <= value < len(rows)):
            continue
        if kind == 'confirm' and not isinstance(value, bool):
            continue
        if kind in ('input', 'secret') and (not isinstance(value, str) or len(value) > 4096 or '\n' in value or '\0' in value):
            continue
        return value


def ask_text(title, secret=False):
    if UI:
        return request('secret' if secret else 'input', title)
    return getpass.getpass(title) if secret else input(title)


def pause(title='Press Enter to return to Recovery. '):
    if UI:
        request('continue', title)
    else:
        input(title)



def say(text):
    if UI:
        NOTES.append(text)
        emit({"event": "status", "text": text})
        return
    print(text, flush=True)
    if SPEECH:
        try:
            subprocess.run(['espeak-ng', '--stdin'], input=text, text=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
        except (OSError, subprocess.TimeoutExpired):
            pass  # the console screen reader remains available when direct speech is unavailable


def choose(title, rows):
    if UI:
        if not rows:
            say({'Which computer?': 'No Starchaser computer was found. Check that its drive is connected and try again.',
                 'Which snapshot?': 'There are no usable snapshots here. Go back to copy your files or repair startup.',
                 'Which backup?': 'No backups were found here. Go back and choose another drive.',
                 'Whose password?': 'No accounts were found on this drive.'}.get(title, 'Nothing is available to choose here. Go back and try another option.'))
        return request("choice", title, rows)
    say(title)
    for index, row in enumerate(rows, 1):
        say(f'{index}. {row}')
    say('0. Back or close. Type a number and press Enter. Type speech to turn speech on or off.')
    while True:
        value = input('Choice: ').strip()
        if value == 'speech':
            global SPEECH
            SPEECH = not SPEECH
            say('Speech on.' if SPEECH else 'Speech off.')
            continue
        if value.isdigit() and 0 <= int(value) <= len(rows):
            return int(value) - 1
        say('Choose a number from the list.')


def confirm(text):
    if UI:
        return request('confirm', text)
    say(text + ' Type YES to continue, or press Enter to go back.')
    return input('Continue: ').strip() == 'YES'


def live_source():
    bundled = Path('/usr/share/starchaser/recovery-payload')
    if all((bundled / name).is_file() for name in rescue.PAYLOAD):
        return bundled
    # The mount path comes from archiso's own state, not an editable environment variable.
    for path in Path('/run/archiso/bootmnt').glob('*/x86_64/airootfs.sfs'):
        return path.parent.parent
    for path in Path('/run/archiso/bootmnt/StarchaserRecovery').glob('*/x86_64/airootfs.sfs'):
        return path.parent.parent
    raise ValueError("The recovery environment couldn't find its original stick or disk payload.")


def guide():
    reset = reset_module()
    reset.BASE = Path('/run/starchaser-rescue')
    def recovery_devices():
        result = reset.command(['lsblk', '--json', '--tree', '--bytes', '--paths', '--output', 'PATH,TYPE,FSTYPE,SIZE,LABEL,MOUNTPOINTS,UUID,PARTUUID,TRAN,RM'])
        if result.returncode:
            raise ValueError("The computer's drives couldn't be read.")
        return json.loads(result.stdout).get('blockdevices', [])
    reset.devices = recovery_devices
    def recovery_available(nodes):
        # An on-disk recovery payload shares a physical disk with the installed
        # root. Exclude mounted partitions themselves, rather than all siblings.
        for node in reset.flatten(nodes):
            if node.get('type') in ('part', 'crypt', 'lvm') and not reset.mounted_live(node):
                yield node
    reset.available = recovery_available

    class Session(reset.Session):
        def open_system(self, device):
            node = reset.validate_device(device)
            if node.get('fstype') != 'btrfs':
                raise ValueError('These recovery tools need a Starchaser system drive. Password reset also supports other layouts.')
            if not self.mount(device, reset.BASE / 'root', 'btrfs', readonly=True, subvol='/'):
                raise ValueError("The system drive couldn't be opened read-only. Nothing was changed.")
            self.state['device'] = device
            self.save()
            if not rescue.inside(reset.BASE / 'root', '@/etc').is_dir():
                raise ValueError('No Starchaser system was found on that drive.')

        def track_reinstall(self, path, active):
            entry = {'path': str(path), 'device': self.state['device']}
            if active:
                self.state['mounts'].append(entry)
            else:
                self.state['mounts'] = [e for e in self.state['mounts'] if e['path'] != str(path)]
            self.save()

        def unmount(self, entry):
            path = entry['path']
            pattern = re.escape(str(reset.BASE / 'root')) + r'/@before-reinstall-[a-f0-9]{32}'
            if not re.fullmatch(pattern, path):
                return super().unmount(entry)
            mounted = reset.command(['findmnt', '-nro', 'SOURCE', '--mountpoint', path])
            if mounted.returncode == 0:
                source = mounted.stdout.strip().split('[')[0]
                if os.path.realpath(source) != os.path.realpath(entry['device']):
                    raise ValueError('The replacement mount changed and was left alone.')
                rescue.checked(['umount', path])
            self.state['mounts'].remove(entry)
            self.save()

        def writable(self):
            system_access(self, reset, readonly=False)

    session = Session()
    try:
        while True:
            action = choose('Starchaser Recovery. Your files stay in place until you approve an action.', [
                'Go back to an earlier snapshot', 'Repair startup', 'Copy my files to another drive',
                'Restore from a backup', 'Reset a password', 'Reinstall Starchaser'])
            if action < 0:
                if UI and confirm('Restart normally? Unplug your recovery USB stick, then choose Continue. Save any work first.'):
                    session.done()
                    rescue.checked(['systemctl', 'reboot'])
                if UI:
                    continue
                return
            session.done()
            if action == 4:
                # The existing password tool owns its own private mounts and code lifecycle.
                session.lock.close()
                reset_password_guide(reset) if UI else reset.interactive(reset.Session())
                session = Session()
                continue
            drives = session.drives()['drives']
            which = choose('Which computer?', [d.get('computer') or d.get('label') or d['device'] for d in drives])
            if which < 0:
                continue
            dev = drives[which]['device']
            if drives[which]['locked']:
                say('This drive needs your disk key. It will not be spoken or saved.')
                dev = session.unlock(dev, ask_text('Disk key: ', secret=True))['device']
            session.open_system(dev)
            top = reset.BASE / 'root'
            root = rescue.inside(top, '@')
            if action == 0:
                snaps = rescue.snapshot_choices(top)
                pick = choose('Which snapshot?', [s['date'] + ' · ' + s['name'] for s in snaps])
                if pick >= 0 and confirm('System software and settings will go back. Your current accounts, passwords and Home folders stay. The old system will be kept. Administrator access or the disk key is required to open this recovery environment.'):
                    say('Going back requires an administrator password every time.')
                    name = ask_text('Administrator account name: ').strip()
                    rescue.authenticate_administrator(root, name, ask_text('Administrator password: ', secret=True))
                    boot = mount_boot(session, reset, root)
                    session.writable()
                    prepared = rescue.prepare_snapshot(top, snaps[pick]['number'])
                    text = rescue.activation_entry(prepared, boot)
                    rescue.activate(root, prepared, boot, 'starchaser-recovered.conf', text)
                    say('The system was switched. Your previous system is kept as ' + prepared.name + '. Restart when you are ready.')
            elif action == 2:
                person = choose_person(session, reset, top)
                if person is None:
                    continue
                target = output_drive(session, reset)
                if target:
                    folder = rescue.copy_files(person['home'], target, owner=(person['uid'], person['gid']))
                    say('Your files were copied to ' + str(folder) + '.')
            elif action == 3:
                restore_guide(session, reset, top)
            else:
                source = rescue.startup_plan(root)
                boot_device = '/dev/disk/by-uuid/' + source.split('=', 1)[1]
                # UUID resolution must identify an available, unmounted partition on the selected computer.
                node = next((n for n in reset.flatten(reset.devices()) if n.get('uuid') == source.split('=', 1)[1]), None)
                if node is None or node.get('fstype') != 'vfat':
                    raise ValueError('The boot partition is in use or unavailable. Nothing was changed.')
                boot_device = node['path']
                if not re.fullmatch(r'/dev/[A-Za-z0-9_+./-]+', boot_device) or not stat.S_ISBLK(os.stat(boot_device).st_mode):
                    raise ValueError('The boot device changed. Nothing was written.')
                boot = reset.BASE / 'probe-boot'
                if action == 1:
                    if not confirm('Startup files will be backed up, then the boot loader and its firmware entry will be repaired. Personal files and system partitions will not be erased.'):
                        continue
                    if not session.mount(boot_device, boot, 'vfat'):
                        raise ValueError("The boot partition couldn't be opened.")
                    layout = rescue.startup_layout(root)
                    esp = mount_boot(session, reset, root, esp=True) if layout['esp'] != layout['boot'] else boot
                    signed = rescue.secure_boot.configuration(root) is not None
                    if signed:
                        session.writable()
                    try:
                        saved = rescue.repair_startup(root, boot, esp=esp)
                    finally:
                        if signed:
                            system_access(session, reset, readonly=True)
                    say('Startup was repaired. Its previous files are kept in ' + str(saved) + '.')
                    if confirm('Add or refresh independent Recovery on this computer? Existing recovery copies stay available. Space is checked before any boot entry changes.'):
                        if signed:
                            session.writable()
                        try:
                            rescue.install_environment(live_source(), boot, root)
                        finally:
                            if signed:
                                system_access(session, reset, readonly=True)
                        say('Independent Recovery was added to the boot menu.')
                elif action == 5:
                    variant = choose('Start fresh', ['Reinstall and keep my files and accounts', 'Erase this computer'])
                    if variant == 1:
                        say('The installer will ask which drive to erase and show its final confirmation. Back up your files first.')
                        session.done()
                        if UI:
                            emit({'event': 'installer'})
                            return
                        rescue.checked(['starchaser-install', 'wizard'])
                    elif variant == 0 and confirm('A fresh copy of system software will be installed. Your Home folders, accounts, passwords and drive encryption stay. Your local software and data will be copied, with Starchaser files refreshed. Extra apps and system settings may need setting up again. The old system, original local software and boot files will be kept. At least 16 GB free and signed package sources are needed.'):
                        say('Reinstalling and keeping accounts requires an administrator password every time.')
                        name = ask_text('Administrator account name: ').strip()
                        rescue.authenticate_administrator(root, name, ask_text('Administrator password: ', secret=True))
                        session.writable()
                        if not session.mount(boot_device, boot, 'vfat'):
                            raise ValueError("The boot partition couldn't be opened.")
                        prepared, entry, text = rescue.prepare_reinstall(top, boot, track_mount=session.track_reinstall)
                        rescue.activate(root, prepared, boot, entry.name, text)
                        say('Starchaser was reinstalled. Your files and accounts were kept. Restart when you are ready.')
            session.done()
            pause()
    finally:
        session.done()
        session.lock.close()


def reset_password_guide(reset):
    session = reset.Session()
    try:
        say('Reset a forgotten password. Your files will be kept.')
        drives = session.drives()['drives']
        pick = choose('Which computer?', [(d.get('computer') or d.get('label') or 'Computer') + (' · Needs its disk key' if d['locked'] else '') for d in drives])
        if pick < 0:
            return
        drive = drives[pick]
        dev = drive['device']
        if drive['locked']:
            dev = session.unlock(dev, ask_text('Disk key', secret=True))['device']
        users = session.accounts(dev)['users']
        pick = choose('Whose password?', [u['full'] or u['name'] for u in users])
        if pick < 0:
            return
        name = users[pick]['name']
        password = reset.account.password_line(io.StringIO(ask_text('New password', secret=True)))
        if password != ask_text('New password again', secret=True):
            raise ValueError("The passwords don't match. Try again.")
        say(reset.account.KEYRING_NOTE)
        replace = confirm('Also reset saved app passwords? Apps will ask you to save your passwords again. A copy of the old saved passwords is kept.')
        if not confirm('Change the sign-in password for ' + name + '? Your files will be kept.'):
            return
        result = session.set_password(name, password, replace)
        say('Password changed for ' + name + '.')
        say(result['keyring']['note'])
        pause()
    finally:
        session.done()
        session.lock.close()


def mount_boot(session, reset, root, esp=False):
    source = rescue.startup_layout(root)['esp'] if esp else rescue.startup_plan(root)
    node = next((n for n in reset.flatten(reset.devices()) if n.get('uuid') == source.split('=', 1)[1]), None)
    if node is None or node.get('fstype') != 'vfat':
        raise ValueError('The boot partition is unavailable. Nothing was changed.')
    device = node['path']
    if not re.fullmatch(r'/dev/[A-Za-z0-9_+./-]+', device) or not stat.S_ISBLK(os.stat(device).st_mode):
        raise ValueError('The boot device changed. Nothing was written.')
    target = reset.BASE / ('probe-efi' if esp else 'probe-boot')
    if not session.mount(device, target, 'vfat'):
        raise ValueError("The boot partition couldn't be opened.")
    return target


def system_access(session, reset, readonly):
    # Recheck the mounted source before changing its access.
    target = reset.BASE / 'root'
    mounted = rescue.checked(['findmnt', '-nro', 'SOURCE', '--mountpoint', target]).stdout.strip().split('[')[0]
    if os.path.realpath(mounted) != os.path.realpath(session.state['device']):
        raise ValueError('The selected drive changed. Nothing was written.')
    entry = next(e for e in session.state['mounts'] if e['path'] == str(target))
    device = session.state['device']
    session.unmount(entry)
    if not session.mount(device, target, 'btrfs', readonly=readonly, subvol='/'):
        raise ValueError("The drive couldn't be opened for the approved change. Nothing was written.")


def recorded_device(reset, source):
    nodes = list(reset.available(reset.devices()))
    if re.fullmatch(r'(?:UUID|PARTUUID)=[A-Za-z0-9-]{1,64}', source):
        key, value = source.split('=', 1)
        matches = [n for n in nodes if str(n.get(key.lower()) or '').lower() == value.lower()]
    elif re.fullmatch(r'/dev/[A-Za-z0-9_+./-]+', source) and not any(p in ('.', '..') for p in source.split('/')):
        matches = [n for n in nodes if os.path.realpath(n['path']) == os.path.realpath(source)]
    else:
        raise ValueError("The recorded Home drive can't be checked. Your files were left alone.")
    if len(matches) > 1:
        raise ValueError('More than one drive has the recorded Home identity. Disconnect the extra copy and try again.')
    if not matches:
        return None
    node = reset.validate_device(matches[0]['path'])
    if source.startswith(('UUID=', 'PARTUUID=')) and str(node.get(key.lower()) or '').lower() != value.lower():
        raise ValueError('The recorded Home drive changed. Nothing was written.')
    return node


def home_device(session, reset, root, source):
    node = recorded_device(reset, source)
    if node is not None:
        return node
    if not source.startswith(('UUID=', 'PARTUUID=', '/dev/mapper/')):
        raise ValueError('The recorded Home drive is unavailable. Connect it before recovering your files.')
    # The installer records Home's encrypted container in crypttab. Opening it
    # uses the existing private mapper lifecycle; the secret stays on stdin.
    crypttab = rescue.inside(root, 'etc/crypttab')
    rows = [line.split() for line in crypttab.read_text().splitlines()
            if line.strip() and not line.lstrip().startswith('#')] if crypttab.is_file() else []
    name = Path(source).name if source.startswith('/dev/mapper/') else 'crypthome'
    matches = [r for r in rows if len(r) >= 3 and r[0] == name]
    if len(matches) != 1:
        raise ValueError('The recorded Home drive is unavailable. Connect it before recovering your files.')
    locked = recorded_device(reset, matches[0][1])
    if locked is None or locked.get('fstype') != 'crypto_LUKS':
        raise ValueError('The recorded Home drive is unavailable. Connect it before recovering your files.')
    say('Your Home drive needs its disk key. It will not be spoken or saved.')
    device = session.unlock(locked['path'], ask_text('Home disk key: ', secret=True))['device']
    node = reset.validate_device(device)
    if source.startswith(('UUID=', 'PARTUUID=')):
        checked = recorded_device(reset, source)
        if checked is None or checked['path'] != node['path']:
            raise ValueError("The unlocked drive doesn't match the recorded Home drive. Nothing was written.")
    return node


def open_home(session, reset, root, writable=False):
    rows = [line.split() for line in rescue.inside(root, 'etc/fstab').read_text().splitlines()
            if line.strip() and not line.lstrip().startswith('#')]
    rows = [r for r in rows if len(r) >= 2 and r[1] == '/home']
    if not rows:
        if writable:
            session.writable()
        return rescue.inside(root, 'home')
    if len(rows) != 1 or len(rows[0]) < 4:
        raise ValueError('The recorded Home layout is unclear. Your files were left alone.')
    source, _, fs, options = rows[0][:4]
    if fs not in ('btrfs', 'ext2', 'ext3', 'ext4', 'xfs', 'exfat', 'vfat', 'ntfs', 'ntfs3'):
        raise ValueError('The recorded Home filesystem is unsupported. Your files were left alone.')
    selectors = {}
    for flag in options.split(','):
        key, _, value = flag.partition('=')
        if key in ('subvol', 'subvolid'):
            if fs != 'btrfs' or key in selectors or not value:
                raise ValueError('The recorded Home subvolume is unclear. Your files were left alone.')
            selectors[key] = re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)
            if any(c == ',' or ord(c) < 32 for c in selectors[key]):
                raise ValueError('The recorded Home subvolume is unsafe. Your files were left alone.')
    if ('subvolid' in selectors and not selectors['subvolid'].isdigit()
            or 'subvol' in selectors and any(p == '..' for p in Path(selectors['subvol']).parts)):
        raise ValueError('The recorded Home subvolume is unsafe. Your files were left alone.')
    node = home_device(session, reset, root, source)
    if node.get('fstype') != fs:
        raise ValueError('The Home drive filesystem changed. Nothing was written.')
    target = reset.BASE / 'probe-home'
    shared = writable and os.path.realpath(node['path']) == os.path.realpath(session.state.get('device', ''))
    if shared:
        # Btrfs cannot add a writable subvolume mount to a read-only superblock.
        system_access(session, reset, readonly=False)
    try:
        if not session.mount(node['path'], target, fs, readonly=not writable, **selectors):
            raise ValueError("The Home drive couldn't be opened. Your files were left alone.")
    finally:
        if shared:
            # Keep the superblock writable through Home, but the discovery view read-only.
            system_access(session, reset, readonly=True)
    return target


def choose_person(session, reset, top, writable=False):
    root = rescue.inside(top, '@')
    people = reset.account.accounts(root)
    pick = choose('Whose files?', [p['full'] or p['name'] for p in people])
    if pick < 0:
        return None
    person = people[pick]
    if not person['home'].startswith('/home/'):
        raise ValueError('That account has a custom Home location. Its files were left alone; ask a helper to open that drive.')
    fields = next(line.split(':') for line in (root / 'etc/passwd').read_text().splitlines() if line.startswith(person['name'] + ':'))
    if len(fields) != 7 or not fields[3].isdigit():
        raise ValueError("That account couldn't be checked. Its files were left alone.")
    home = open_home(session, reset, root, writable=writable)
    folder = rescue.inside(home, person['home'][6:])
    if not folder.is_dir():
        raise ValueError('That account has no folder on the recorded Home drive. Your files were left alone.')
    return {'uid': person['uid'], 'gid': int(fields[3]), 'home': folder}


def output_drive(session, reset):
    tree = reset.devices()
    external = []
    for disk in tree:
        family = list(reset.flatten([disk]))
        sources = {e['device'] for e in session.state['mounts']} | {session.state.get('device')}
        if sources.intersection(n.get('path') for n in family) or any(reset.mounted_live(n) for n in family):
            continue
        if not (disk.get('tran') == 'usb' or disk.get('rm')):
            continue
        external.extend(n for n in reset.available([disk]) if n.get('type') == 'part' and n.get('fstype') in ('ext4', 'btrfs', 'exfat', 'vfat', 'ntfs', 'ntfs3'))
    pick = choose('Copy to which external drive?', [str(n.get('label') or n['path']) for n in external])
    if pick < 0:
        return None
    node = reset.validate_device(external[pick]['path'])
    if not confirm('Your Home folders will be copied into a new folder on this external drive. Existing files there stay as they are.'):
        return None
    target = reset.BASE / 'probe-output'
    if not session.mount(node['path'], target, node['fstype']):
        raise ValueError("The external drive couldn't be opened.")
    return target


def restore_guide(session, reset, top):
    # Open the backup source read-only; restored data goes into a new folder on Home.
    nodes = [n for n in reset.available(reset.devices()) if n.get('type') == 'part' and n.get('fstype') in ('ext4', 'btrfs', 'exfat', 'vfat', 'ntfs', 'ntfs3')]
    pick = choose('Which drive holds the backup?', [n.get('label') or n['path'] for n in nodes])
    if pick < 0:
        return
    node = reset.validate_device(nodes[pick]['path'])
    where = reset.BASE / 'probe-backup'
    if not session.mount(node['path'], where, node['fstype'], readonly=True):
        raise ValueError("The backup drive couldn't be opened.")
    base = rescue.inside(where, 'Starchaser Backups')
    owners = [p for p in base.iterdir() if not p.is_symlink() and (p / 'config').is_file()]
    pick = choose('Whose backups are these?', [p.name for p in owners])
    if pick < 0:
        return
    repo = owners[pick]
    password = ask_text('Backup password (Enter if none): ', secret=True)
    env = {k: v for k, v in os.environ.items() if not k.startswith('RESTIC_')}
    env.update(RESTIC_REPOSITORY=str(repo), RESTIC_PASSWORD=password)
    flags = [] if password else ['--insecure-no-password']
    result = rescue.checked(['restic', *flags, 'snapshots', '--json', '--no-lock'], env=env)
    snaps = sorted(json.loads(result.stdout), key=lambda s: s.get('time', ''), reverse=True)
    pick = choose('Which backup?', [backup_date(s.get('time', '')) for s in snaps])
    if pick < 0 or not confirm('Files from this backup will be put into a new folder in Home. Your current files will not be replaced. You can choose which files to keep after restarting normally.'):
        return
    person = choose_person(session, reset, top, writable=True)
    if person is None:
        return
    target = person['home']
    folder, count = rescue.restore_backup(repo, password, snaps[pick]['id'], target, owner=(person['uid'], person['gid']))
    say(f'Restored {count} files into {folder.name} in Home. Your current files were kept.')


def backup_date(value):
    from datetime import datetime
    try:
        return datetime.fromisoformat(value.replace('Z', '+00:00')).astimezone().strftime('%b %-d, %Y %-I:%M %p')
    except ValueError:
        return 'Unknown date'


def close_graphical_session(process, runtime):
    # Session bus services can outlive the window and keep portal mounts in the private runtime folder.
    try:
        os.killpg(process.pid, signal.SIGTERM)
    except ProcessLookupError:
        pass
    for name in ('doc', 'gvfs'):
        target = Path(runtime) / name
        result = subprocess.run(['findmnt', '-rn', '-o', 'FSTYPE', '--mountpoint', str(target)], capture_output=True, text=True)
        if result.returncode == 0 and result.stdout.strip() in ('fuse.portal', 'fuse.gvfsd-fuse'):
            subprocess.run(['umount', '-l', str(target)], capture_output=True, check=False)


def main():
    parser = argparse.ArgumentParser(prog="starchaser rescue", description=__doc__)
    parser.add_argument('--install-environment', metavar='BOOT', type=Path)
    parser.add_argument('--installed-root', metavar='ROOT', type=Path)
    parser.add_argument('--ui', action='store_true', help='use the graphical guide request/reply protocol')
    parser.add_argument('--graphical', action='store_true', help='start the full-screen recovery session, with console fallback')
    parser.add_argument('--demo', action='store_true', help='show a read-only demonstration without opening any drives')
    args = parser.parse_args()
    if args.install_environment and args.installed_root is None:
        parser.error('--install-environment needs --installed-root so startup signing can be checked')
    global UI
    UI = args.ui
    if args.demo:
        if not UI:
            parser.error('--demo needs --ui')
        try:
            while True:
                choice = choose('Starchaser Recovery', ['Go back to an earlier snapshot', 'Repair startup', 'Copy my files to another drive', 'Restore from a backup', 'Reset a password', 'Reinstall Starchaser'])
                if choice < 0:
                    say('This is a preview. Restart is available when started from Recovery.'); pause()
                else:
                    say('This is a preview. No drives are opened and no files can change.'); pause()
        except (EOFError, KeyboardInterrupt):
            return 0
    if os.geteuid() != 0 or not Path('/run/archiso').is_dir():
        parser.exit(1, 'Start Starchaser Recovery from the boot menu or your recovery USB stick.\n')
    try:
        if args.graphical and shutil.which('labwc') and shutil.which('qs'):
            page = REPO / 'config/quickshell/recovery'
            if not (page / 'shell.qml').is_file():
                page = Path('/usr/share/starchaser/repo/config/quickshell/recovery')
            with tempfile.TemporaryDirectory(prefix='starchaser-recovery-', dir='/run') as runtime:
                env = dict(os.environ, XDG_RUNTIME_DIR=runtime, QT_LINUX_ACCESSIBILITY_ALWAYS_ON='1', QS_DISABLE_CRASH_HANDLER='1', STARCHASER_QML_APP='recovery')
                outcome = Path(runtime) / 'outcome'
                startup = shlex.join(['sh', '-c', 'qs -p "$1"; code=$?; printf "%s" "$code" > "$2"; labwc --exit', 'sh', str(page), str(outcome)])
                process = subprocess.Popen(['dbus-run-session', '--', 'labwc', '-C', runtime, '-s', startup], env=env, start_new_session=True)
                try:
                    code = process.wait()
                finally:
                    close_graphical_session(process, runtime)
                if code == 0 and outcome.is_file() and outcome.read_text() == '0':
                    return 0
            say('The graphical guide could not open. The spoken text guide is ready.')
        def interrupted(*_):
            raise EOFError()
        for signum in (signal.SIGTERM, signal.SIGHUP):
            signal.signal(signum, interrupted)
        if args.install_environment:
            rescue.install_environment(live_source(), args.install_environment, args.installed_root)
            say('Independent recovery was added to the boot menu.')
        else:
            while True:
                try:
                    guide()
                    break
                except ValueError as error:
                    say(str(error))
                    pause()
    except (ValueError, OSError) as error:
        parser.exit(1, str(error) + '\n')
    except (EOFError, KeyboardInterrupt):
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main())
