#!/usr/bin/env python3
"""Boot an ISO payload and test ordinary CLI writes after a root API commit.

The VM has no writable persistent disk. Keys are generated inside the guest
and never printed. This tests runtime configuration, not WireGuard traffic.
A test-only secondary debug console starts the normal Carrier login shell via
runuser, without requiring or altering the ISO's default password.
"""

import argparse
import base64
import pathlib
import re
import shlex
import subprocess
import tempfile

import pexpect


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('iso', type=pathlib.Path)
    parser.add_argument('--log', type=pathlib.Path, required=True)
    parser.add_argument('--memory', type=int, default=2048,
                        help='guest RAM in MiB (default: 2048)')
    parser.add_argument('--inject-boot-failure', action='store_true',
                        help='start from emergency mode and inject a failed loader')
    parser.add_argument('--source-overlay', type=pathlib.Path,
                        help='test-only rootfs-shaped directory of candidate files')
    parser.add_argument('--guest-test', type=pathlib.Path,
                        help='additional Python integration test on a read-only fixture CD')
    parser.add_argument('--guest-data', type=pathlib.Path, action='append', default=[],
                        help='private read-only fixture input (never added to the tested ISO)')
    parser.add_argument('--guest-only', action='store_true',
                        help='run only the supplied fixture after verifying successful boot')
    parser.add_argument('--extra-nic', action='store_true',
                        help='add a second independent virtio PCI NIC for scoped hotplug tests')
    parser.add_argument('--cpus', type=int, default=2)
    parser.add_argument('--nht-recreate-cycles', type=int, default=1,
                        help='repeat VRF delete/recreate validation to diagnose intermittent failures')
    parser.add_argument('--cli-migration', action='store_true',
                        help='exercise native paste, real completion, saved edits and limited SSH login')
    parser.add_argument('--retired-vbash', action='store_true',
                        help='require carrier-cli only, no old executable, symlink or account shell')
    parser.add_argument('--retire-vbash-overlay', action='store_true',
                        help='candidate-only deletion in disposable VM; NEVER final ISO acceptance')
    parser.add_argument('--boot-compatibility', action='store_true',
                        help='verify packaged native units and resolved compatibility warnings')
    parser.add_argument('--operator-capability-overlay', action='store_true',
                        help='test-only candidate cap_setuid fix; NEVER use for final ISO acceptance')
    args = parser.parse_args()
    if args.memory < 256:
        parser.error('--memory must be at least 256 MiB')
    if args.retire_vbash_overlay and not args.source_overlay:
        parser.error('--retire-vbash-overlay requires --source-overlay')
    iso = args.iso.resolve(strict=True)
    with tempfile.TemporaryDirectory(prefix='configsession-qemu-') as tmp:
        for name in ('vmlinuz', 'initrd.img'):
            subprocess.run(['xorriso', '-osirrox', 'on', '-indev', str(iso),
                            '-extract_single', f'/live/{name}', f'{tmp}/{name}'],
                           check=True, stdout=subprocess.DEVNULL,
                           stderr=subprocess.DEVNULL)
        command = ['qemu-system-x86_64', '-enable-kvm', '-m', str(args.memory), '-smp', str(args.cpus),
                   '-display', 'none', '-monitor', 'none',
                   '-serial', f'file:{args.log.resolve()}.boot',
                   '-chardev', 'stdio,id=qacli,signal=off', '-serial', 'chardev:qacli',
                   '-no-reboot', '-boot', 'd', '-cdrom', str(iso),
                   '-netdev', 'user,id=wan', '-device', 'virtio-net-pci,netdev=wan',
                   '-kernel', f'{tmp}/vmlinuz', '-initrd', f'{tmp}/initrd.img',
                   '-append', 'boot=live components hostname=carrier-router '
                   'username=live nopersistence noautologin nonetworking '
                   'union=overlay console=ttyS0,115200 net.ifnames=0 biosdevname=0 '
                   'systemd.debug_shell=ttyS1']
        overlay_files = []
        if args.extra_nic:
            command += ['-cpu', 'host', '-netdev', 'user,id=hotplug', '-device', 'virtio-net-pci,netdev=hotplug']
        if args.guest_test:
            fixture = args.guest_test.resolve(strict=True)
            data_files = [path.resolve(strict=True) for path in args.guest_data]
            names = [path.name for path in data_files]
            if len(names) != len(set(names)) or 'guest-test.py' in names:
                raise ValueError('Duplicate fixture input name')
            subprocess.run(['xorriso', '-as', 'mkisofs', '-quiet', '-o',
                            f'{tmp}/fixture.iso', '-graft-points',
                            f'guest-test.py={fixture}',
                            *[f'{path.name}={path}' for path in data_files]], check=True)
            command += ['-drive', f'file={tmp}/fixture.iso,if=virtio,format=raw,readonly=on']
        if args.source_overlay:
            overlay = args.source_overlay.resolve(strict=True)
            overlay_files = [p.relative_to(overlay) for p in overlay.rglob('*')
                             if p.is_file() and not p.is_symlink()]
            if not overlay_files:
                raise ValueError('Source overlay is empty')
            subprocess.run(['xorriso', '-as', 'mkisofs', '-quiet', '-o',
                            f'{tmp}/overlay.iso', str(overlay)], check=True,
                           stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
            command += ['-drive', f'file={tmp}/overlay.iso,media=cdrom,index=3,readonly=on']
        if args.inject_boot_failure or args.source_overlay:
            # Stop before normal startup so injection cannot race the loader.
            # Only this disposable VM's overlay is modified, never the ISO.
            command[command.index('-append') + 1] += ' systemd.unit=emergency.target'
        with args.log.open('w') as log:
            child = pexpect.spawn(command[0], command[1:], encoding='utf-8',
                                  codec_errors='replace', timeout=180,
                                  dimensions=(40, 240))
            child.logfile_read = log
            try:
                child.expect(r'# ', timeout=300)
                if args.source_overlay:
                    commands = ['mkdir -p /run/qa-overlay && '
                                'mount -o ro /dev/sr1 /run/qa-overlay']
                    commands += [
                        f'mkdir -p {shlex.quote("/" + str(path.parent))} && '
                        f'cp {shlex.quote("/run/qa-overlay/" + str(path))} '
                        f'{shlex.quote("/" + str(path))}' for path in overlay_files]
                    if args.retire_vbash_overlay:
                        commands.append('test -x /bin/carrier-cli && rm -f /bin/vbash')
                    commands.append('python3 /usr/lib/python3/dist-packages/vyos/xml_ref/update_cache.py')
                    # Bound terminal input as overlays gain new CLI definitions.
                    for command_line in commands:
                        child.sendline(command_line +
                            ' && printf "\\nOVERLAY_QA_PASS\\n" '
                            '|| printf "\\nOVERLAY_QA_FAIL\\n"')
                        child.expect(r'\r*\nOVERLAY_QA_(PASS|FAIL)\r*\n')
                        if child.match.group(1) != 'PASS':
                            raise RuntimeError('Candidate overlay installation failed')
                        child.expect(r'# ')
                    if not args.inject_boot_failure:
                        child.sendline('systemctl start --no-block default.target; '
                                       'echo; echo DEFAULT_TEST_STARTED')
                        child.expect(r'\r*\nDEFAULT_TEST_STARTED\r*\n')
                        child.expect(r'# ')
                if args.inject_boot_failure:
                    payload = base64.b64encode(
                        b'#!/bin/sh\necho CARRIER_QA_LOADER_FAILED >&2\nexit 42\n'
                    ).decode()
                    child.sendline(
                        f'printf %s {payload} | base64 -d > '
                        '/usr/libexec/vyos/vyos-boot-config-loader.py; '
                        'systemctl start --no-block default.target; '
                        'echo; echo FAILURE_TEST_STARTED')
                    child.expect(r'\r*\nFAILURE_TEST_STARTED\r*\n')
                    child.expect(r'# ')
                    child.sendline(
                        'for i in $(seq 1 180); do '
                        'systemctl is-failed --quiet vyos-router.service && break; '
                        'test "$(systemctl show -p SubState --value vyos-router.service)" = exited && break; '
                        'sleep 1; done; '
                        'systemctl is-failed --quiet vyos-router.service && '
                        'journalctl -b -u vyos-router.service --no-pager | '
                        'grep -q CARRIER_QA_LOADER_FAILED && '
                        'journalctl -b -u vyos-router.service --no-pager | '
                        'grep -q "Carrier Router configuration failed" && '
                        '! journalctl -b -u vyos-router.service --no-pager | '
                        'grep -q "Carrier Router READY" '
                        '&& printf "\\nFAILURE_QA_PASS\\n" '
                        '|| printf "\\nFAILURE_QA_FAIL\\n"')
                    child.expect(r'\r*\nFAILURE_QA_(PASS|FAIL)\r*\n', timeout=240)
                    if child.match.group(1) != 'PASS':
                        raise RuntimeError('Injected boot failure was not reported correctly')
                    child.expect(r'# ')
                    print('PASS: injected loader exit 42 makes real vyos-router.service '
                          'fail and does not report READY', flush=True)
                    child.sendline('/usr/bin/systemctl poweroff --force')
                    child.expect(pexpect.EOF, timeout=60)
                    return
                child.sendline('while ! test -e /run/vyos/boot-config-status; do sleep 1; done; '
                               'echo; echo BOOT_STATUS_READY')
                child.expect(r'\r*\nBOOT_STATUS_READY\r*\n', timeout=300)
                child.expect(r'# ')
                if args.guest_only:
                    if not args.guest_test:
                        raise ValueError('--guest-only requires --guest-test')
                    child.sendline(
                        'test "$(cat /run/vyos/boot-config-status)" = 0 && '
                        'mkdir -p /run/qa-fixture && '
                        'mount -o ro /dev/vda /run/qa-fixture && '
                        'python3 /run/qa-fixture/guest-test.py && '
                        'echo FIXTURE_PASS || echo FIXTURE_FAIL')
                    child.expect(r'\r*\nFIXTURE_(PASS|FAIL)\r*\n', timeout=600)
                    if child.match.group(1) != 'PASS':
                        raise RuntimeError('Guest fixture failed')
                    child.expect(r'# ')
                    child.sendline('/usr/bin/systemctl poweroff --force')
                    child.expect(pexpect.EOF, timeout=180)
                    print('PASS: boot and isolated guest fixture', flush=True)
                    return
                child.sendline('runuser -l Carrier')
                child.expect(r'Carrier@[^\r\n]*\$')

                def run(command, timeout=180):
                    # Configuration commands consume the remaining words as
                    # their CLI path, including shell &&/|| operators.
                    if command.split()[0] in ('set', 'delete', 'commit'):
                        child.sendline(command)
                        # A wrapped input line may redraw the prompt after CR
                        # and cursor-up, before the command has even run. Only
                        # consume a fresh prompt on a new output line; sending
                        # the next command during commit can be flushed by CLI.
                        child.expect(r'\r*\nCarrier@[^\r\n]*# ')
                        if re.search(r'\b(failed|invalid|error)\b', child.before,
                                     flags=re.IGNORECASE):
                            raise RuntimeError(f'Guest CLI failed: {command}')
                        return
                    # Require a success marker on its own line, not echoed input.
                    # VyOS binds the '?' key to CLI help even inside a typed
                    # shell command, so do not send the shell's status variable.
                    child.sendline(command + ' && printf "\\nQA_PASS\\n" || printf "\\nQA_FAIL\\n"')
                    child.expect(r'\r*\nQA_(PASS|FAIL)\r*\n', timeout=timeout)
                    if child.match.group(1) != 'PASS':
                        child.expect(r'Carrier@[^\r\n]*[#$]')
                        child.sendline(
                            'sleep 3; sudo vtysh -c "show ip nht vrf qa-dc json"; '
                            'ip -j link show qa-dc; '
                            'show vrf; '
                            'sudo vtysh -c "show running-config" | '
                            'sed -n "/^vrf qa-/,/^exit-vrf/p"; '
                            'sudo sed -n "/^vrf qa-/,/^exit-vrf/p" '
                            '/run/frr/config/vyos.frr.conf; '
                            'sudo journalctl -b -u vyos-configd --no-pager -n 160; '
                            'echo; echo FAILURE_DIAGNOSTICS_DONE')
                        child.expect(r'\r*\nFAILURE_DIAGNOSTICS_DONE\r*\n')
                        raise RuntimeError(f'Guest command failed: {command}')
                    child.expect(r'Carrier@[^\r\n]*[#$]')

                run('test "$(cat /run/vyos/boot-config-status)" = 0')
                run('test "$(id -u)" != 0')
                if args.operator_capability_overlay:
                    run('sudo setcap cap_setuid=ep /usr/bin/vyos-op-run')

                def check_nht(vrf='default', enabled=True):
                    for afi, key in (('ip', 'ipv4'), ('ipv6', 'ipv6')):
                        scope = '' if vrf == 'default' else f' vrf {vrf}'
                        query = f'.["{vrf}"].{key}.resolveViaDefault == {str(enabled).lower()}'
                        run(f'sudo vtysh -c "show {afi} nht{scope} json" | '
                            f'jq -e {shlex.quote(query)} > /dev/null')

                check_nht()
                root_commit = (
                    'import os; from vyos.configsession import ConfigSession; '
                    'os.umask(0o077); s=ConfigSession(os.getpid()); '
                    's.commit(); s._finalizer()')
                run('sudo python3 -c ' + shlex.quote(root_commit))
                check_group = (
                    'import grp,pathlib; g=grp.getgrnam("vyattacfg").gr_gid; '
                    'p=pathlib.Path("/opt/vyatta/config/active"); '
                    'assert all(x.stat().st_gid == g and x.stat().st_mode & 0o020 '
                    'for x in p.rglob("*"))')
                run('sudo python3 -c ' + shlex.quote(check_group))
                child.sendline('configure')
                child.expect(r'Carrier@[^\r\n]*#')
                run('set interfaces wireguard wg65430 private-key "$(wg genkey)"')
                run('set interfaces wireguard wg65430 address 192.0.2.1/32')
                run('set interfaces wireguard wg65430 description permission-test')
                run('commit')
                run('test -d /sys/class/net/wg65430')
                run('FIRST_PUBLIC_KEY=$(sudo wg show wg65430 public-key)')
                run('sudo python3 -c ' + shlex.quote(root_commit))
                run('set interfaces wireguard wg65430 private-key "$(wg genkey)"')
                run('set interfaces wireguard wg65430 description permission-retest')
                run('commit')
                run('test "$FIRST_PUBLIC_KEY" != "$(sudo wg show wg65430 public-key)"')
                run('test "$(cat /sys/class/net/wg65430/ifalias)" = permission-retest')
                run('sudo python3 -c ' + shlex.quote(check_group))
                run('delete interfaces wireguard wg65430')
                run('commit')
                run('test ! -d /sys/class/net/wg65430')

                # Check runtime values, not just rendered command strings.
                # Explicit opt-outs must remain independent per AF and VRF,
                # and deleting them must restore the default through reload.
                run('set vrf name qa-nht table 65430')
                run('set system ip nht no-resolve-via-default')
                run('set system ipv6 nht no-resolve-via-default')
                run('commit')
                check_nht(enabled=False)
                check_nht('qa-nht')
                run('delete system ip nht no-resolve-via-default')
                run('delete system ipv6 nht no-resolve-via-default')
                run('set vrf name qa-nht ip nht no-resolve-via-default')
                run('set vrf name qa-nht ipv6 nht no-resolve-via-default')
                run('commit')
                check_nht()
                check_nht('qa-nht', enabled=False)
                run('delete vrf name qa-nht ip nht no-resolve-via-default')
                run('delete vrf name qa-nht ipv6 nht no-resolve-via-default')
                run('set interfaces ethernet eth0 description nht-reload-test')
                run('commit')
                check_nht()
                check_nht('qa-nht')
                run('set system frr profile datacenter')
                run('commit')
                run('sudo systemctl restart frr.service')
                run('systemctl is-active --quiet frr.service')
                # A newly created VRF must use Carrier's explicit defaults
                # even after daemons start with the datacenter profile.
                run('set vrf name qa-dc table 65429')
                run('commit')
                check_nht()
                check_nht('qa-dc')
                for cycle in range(args.nht_recreate_cycles):
                    run('delete vrf name qa-dc')
                    run('commit')
                    check_nht('qa-nht')
                    run('test ! -d /sys/class/net/qa-dc')
                    run('! sudo vtysh -c "show running-config" | grep -q "^vrf qa-dc"')
                    run('set vrf name qa-dc table 65429')
                    run('commit')
                    check_nht('qa-dc')
                    print(f'PASS: datacenter VRF delete/recreate cycle {cycle + 1}', flush=True)
                run('delete system frr profile')
                run('delete vrf name qa-dc')
                run('delete vrf name qa-nht')
                run('delete interfaces ethernet eth0 description')
                run('commit')
                run('test ! -d /sys/class/net/qa-nht && test ! -d /sys/class/net/qa-dc')
                run('for i in $(seq 1 30); do '
                    '! sudo vtysh -c "show running-config" | grep -q "^vrf qa-" && break; '
                    'sleep 1; done; '
                    '! sudo vtysh -c "show running-config" | grep -q "^vrf qa-"')
                run('sudo systemctl restart frr.service')
                check_nht()
                child.sendline('exit')
                child.expect(r'Carrier@[^\r\n]*\$')
                run('sudo modprobe jool && sudo modprobe ipt_NETFLOW && sudo modprobe r8152')
                run('test -z "$(systemctl --failed --no-legend)"')
                if args.boot_compatibility:
                    run('test "$(readlink /etc/systemd/system-generators/systemd-ssh-generator)" = /dev/null')
                    # Reproduce the target's loaded VSOCK stack without a guest
                    # CID. Test real systemd generator discovery, not a direct
                    # invocation that would bypass the mask by definition.
                    run('sudo modprobe vsock && test -c /dev/vsock')
                    run('test -f /usr/share/zoneinfo/right/UTC')
                    for unit in ('qat_service', 'stunnel4', 'vmtouch', 'wide-dhcpv6-client'):
                        run(f'test "$(systemctl show {unit}.service -p FragmentPath --value)" '
                            f'= /usr/lib/systemd/system/{unit}.service')
                    run('sudo systemctl daemon-reload')
                    run('! sudo journalctl -b --no-pager -o cat | grep -E '
                        + shlex.quote('lacks a native systemd unit file|compatibility logic is deprecated|'
                                      'Evaluating unset environment variable.*(DAEMON_ARGS|OPTIONS)|'
                                      'right/UTC.*(not found|No such file)|'
                                      'Failed to query local AF_VSOCK CID'))
                    run('test -z "$(find /run/systemd/generator /run/systemd/generator.early '
                        '/run/systemd/generator.late -name \'sshd-*.socket\' -print)"')
                    print('PASS: native service units, time-zone data and boot compatibility warnings', flush=True)
                if args.cli_migration:
                    run('test "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}" = 5.3')
                    if args.retired_vbash:
                        run('test -x /bin/carrier-cli && test "$SHELL" = /bin/carrier-cli')
                        run('test ! -e /bin/vbash && test ! -L /bin/vbash && '
                            'test ! -e /usr/bin/vbash && test ! -L /usr/bin/vbash')
                        run('! command -v vbash')
                        run('! grep -E "/(usr/)?bin/vbash" /etc/passwd /etc/shells')
                        run('test "$(readlink /proc/$$/exe)" = /usr/bin/carrier-cli')
                    # Simulate a retained pre-upgrade .inputrc, then enter a fresh
                    # login session. Shared CLI initialization must override off.
                    run("printf 'set enable-bracketed-paste off\\n' > ~/.inputrc")
                    child.sendline('exit')
                    child.expect(r'# ')
                    child.sendline('TERM=xterm-256color runuser -l Carrier')
                    child.expect(r'Carrier@[^\r\n]*\$')
                    run("bind -v | grep -q '^set enable-bracketed-paste on'")
                    child.send('sho\t')
                    child.expect('show')
                    child.sendcontrol('c')
                    child.expect(r'Carrier@[^\r\n]*\$')
                    child.send('show \x3f')
                    child.expect('Possible completions:')
                    child.sendcontrol('c')
                    child.expect(r'Carrier@[^\r\n]*\$')
                    child.sendline('configure')
                    child.expect(r'Carrier@[^\r\n]*#')
                    child.send('\x1b[200~set interfaces ethernet eth0 description '
                               '"Carrier;Bash&5|paste"\ncommit\x1b[201~')
                    # No newline-triggered commit until the user presses Enter.
                    child.expect(pexpect.TIMEOUT, timeout=1)
                    child.sendline('')
                    child.expect(r'Carrier@[^\r\n]*#', timeout=180)
                    child.sendline('')
                    child.expect(r'Carrier@[^\r\n]*#', timeout=180)
                    run('test "$(cat /sys/class/net/eth0/ifalias)" = "Carrier;Bash&5|paste"')
                    run('save /config/cli-migration-qa.boot')
                    run('sudo grep -q "Carrier;Bash&5|paste" /config/cli-migration-qa.boot')
                    run('delete interfaces ethernet eth0 description')
                    run('commit')
                    run('test -z "$(cat /sys/class/net/eth0/ifalias)"')
                    child.sendline('exit')
                    child.expect(r'Carrier@[^\r\n]*\$')
                    run('sudo ssh-keygen -q -t ed25519 -N "" -f /run/qa-cli-key')
                    # Provision a real configured operator, including the
                    # per-command policy consumed by the operational runner.
                    operator_setup = (
                        'import os,secrets,pathlib; from vyos.configsession import ConfigSession; '
                        's=ConfigSession(os.getpid()); '
                        'b=["system","login"]; u=b+["user","qa-cli-limited"]; '
                        's.set(b+["operator-group","qa-readonly","command-policy","allow"],value="show version"); '
                        's.set(u+["operator","group"],value="qa-readonly"); '
                        's.set(u+["authentication","plaintext-password"],value=secrets.token_hex(32)); '
                        'k=u+["authentication","public-keys","qa"]; '
                        's.set(k+["type"],value="ssh-ed25519"); '
                        's.set(k+["key"],value=pathlib.Path("/run/qa-cli-key.pub").read_text().split()[1]); '
                        's.set(["service","ssh","port"],value="2222"); '
                        's.set(["service","ssh","listen-address"],value="127.0.0.1"); '
                        's.set(["service","ssh","disable-password-authentication"]); '
                        's.commit(); s._finalizer()')
                    run('sudo python3 -c ' + shlex.quote(operator_setup))
                    # Test the actual CLI-owned TCP service, not a separately
                    # launched sshd that could hide a service-policy regression.
                    run('systemctl is-active --quiet ssh@default.service')
                    run('sudo systemctl daemon-reload && systemctl is-active --quiet ssh@default.service')
                    child.sendline('sudo ssh -tt -p 2222 -i /run/qa-cli-key '
                                   '-o StrictHostKeyChecking=accept-new '
                                   '-o UserKnownHostsFile=/run/qa-cli-known-hosts '
                                   'qa-cli-limited@127.0.0.1')
                    child.expect(r'qa-cli-limited@[^\r\n]*>', timeout=30)
                    child.sendline('show version')
                    child.expect(r'qa-cli-limited@[^\r\n]*>', timeout=30)
                    if 'Carrier Router' not in child.before or re.search(
                            r'Internal error|Invalid command|not assigned', child.before):
                        raise RuntimeError('Configured operator cannot run allowed show version')
                    for denied in ('sudo id', 'bash', 'configure', 'show interfaces', 'show version; id',
                                   'show version > /run/qa-cli-denied'):
                        child.sendline(denied)
                        child.expect(r'qa-cli-limited@[^\r\n]*>')
                        if not re.search('Invalid command|not allowed|permission denied|do not have.*permission',
                                         child.before, re.IGNORECASE):
                            raise RuntimeError(f'Limited CLI accepted: {denied}: {child.before!r}')
                    child.send('\x1b[200~show version\nsudo id\x1b[201~')
                    child.sendline('')
                    child.expect(r'qa-cli-limited@[^\r\n]*>', timeout=30)
                    output = child.before
                    if 'Invalid command' not in output:
                        child.expect(r'qa-cli-limited@[^\r\n]*>')
                        output += child.before
                    if 'Invalid command' not in output or 'uid=0' in output:
                        raise RuntimeError('Limited multiline SSH paste bypassed policy')
                    child.sendline('exit')
                    child.expect(r'Carrier@[^\r\n]*\$')
                    run('test ! -e /run/qa-cli-denied')
                    # The existing runner uses getlogin(), so its direct-call
                    # test needs a real login/utmp record, not a runuser shim.
                    direct_ssh = ('sudo -n ssh -tt -p 2222 -i /run/qa-cli-key '
                                  '-o BatchMode=yes -o StrictHostKeyChecking=yes '
                                  '-o UserKnownHostsFile=/run/qa-cli-known-hosts '
                                  'qa-cli-limited@127.0.0.1')
                    run(direct_ssh + ' /usr/bin/vyos-op-run show version | grep -q "^Version:.*Carrier Router"')
                    for denied in ('show interfaces', 'configure', 'execute shell', 'id'):
                        run('! ' + direct_ssh + ' /usr/bin/vyos-op-run ' + denied)
                    print('PASS: Bash 5.3 real CLI completion/help, retained inputrc, '
                          'multiline paste, save/edit/delete and restricted SSH login', flush=True)
                if args.guest_test:
                    run('sudo mkdir -p /run/qa-fixture && sudo mount -o ro /dev/vda /run/qa-fixture')
                    run('sudo python3 /run/qa-fixture/guest-test.py', timeout=600)
                print('PASS: boot, root restrictive-umask commits, ordinary-user '
                      'WireGuard set/commit/edit/delete, global/VRF dual-stack NHT '
                      'defaults and opt-out/delete/reload, module loads, systemd', flush=True)
                child.sendline('sudo poweroff')
                child.expect(pexpect.EOF, timeout=180 if args.guest_test else 60)
            finally:
                child.close(force=True)


if __name__ == '__main__':
    main()
