#!/usr/bin/env python3
"""Actual ISO install + disk boot + image upgrade under umask 077; no overlays."""

import argparse
from pathlib import Path
import shlex
import subprocess
import tempfile
import socket
import json
import time

import pexpect


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('iso', type=Path)
    parser.add_argument('--version', required=True)
    parser.add_argument('--log', type=Path, required=True)
    parser.add_argument('--check-migration', action='store_true',
                        help='also require packaged BGP migration to preserve IPv6-only activation')
    parser.add_argument('--check-arp-ignore', action='store_true',
                        help='preserve and apply explicit ARP ignore across install/upgrade boots')
    args = parser.parse_args()
    iso = args.iso.resolve(strict=True)
    before = 'qa-before-' + args.version
    installer = '/usr/libexec/vyos/op_mode/image_installer.py'
    prompt = r'Carrier@[^\r\n]*\$'

    with tempfile.TemporaryDirectory(prefix='image-umask-', dir=iso.parent) as tmp:
        root = Path(tmp)
        disk = root / 'guest.qcow2'
        subprocess.run(['qemu-img', 'create', '-f', 'qcow2', str(disk), '8G'], check=True)
        for name in ('vmlinuz', 'initrd.img'):
            subprocess.run(['xorriso', '-osirrox', 'on', '-indev', str(iso),
                            '-extract_single', '/live/' + name, str(root / name)],
                           check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        common = ['qemu-system-x86_64', '-enable-kvm', '-m', '1024', '-smp', '2',
                  '-display', 'none', '-monitor', 'none', '-no-reboot',
                  '-qmp', f'unix:{root}/qmp.sock,server=on,wait=off',
                  '-drive', f'file={disk},if=virtio,format=qcow2', '-cdrom', str(iso),
                  '-netdev', 'user,id=wan', '-device', 'virtio-net-pci,netdev=wan']
        with args.log.open('w') as log:
            def spawn(live):
                command = list(common)
                if live:
                    command += ['-serial', f'file:{args.log.resolve()}.live-boot',
                                '-chardev', 'stdio,id=qacli,signal=off', '-serial', 'chardev:qacli',
                                '-kernel', str(root / 'vmlinuz'), '-initrd', str(root / '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']
                else:
                    # Deliberately use the installed GRUB and disk, not direct kernel boot.
                    command += ['-boot', 'c', '-serial', 'stdio']
                return pexpect.spawn(command[0], command[1:], encoding='utf-8',
                                     codec_errors='replace', timeout=300, logfile=log)

            def run(child, command, expected_prompt, timeout=180):
                child.sendline(command + r' && printf "\nQA_COMMAND_PASS\n" || printf "\nQA_COMMAND_FAIL\n"')
                child.expect(r'\r*\nQA_COMMAND_(PASS|FAIL)\r*\n', timeout=timeout)
                if child.match.group(1) != 'PASS':
                    raise RuntimeError('Guest command failed; inspect log')
                child.expect(expected_prompt)

            def stop(child, sudo=False):
                child.sendline(('sudo ' if sudo else '') +
                               '/bin/sh -c "sync; systemctl poweroff --force --force"')
                child.expect(pexpect.EOF, timeout=90)
                child.close()

            def login(child):
                try:
                    child.expect(r'[Ll]ogin:', timeout=150)
                except pexpect.TIMEOUT:
                    child.sendline('')
                    child.expect(r'[Ll]ogin:', timeout=150)
                child.sendline('Carrier')
                child.expect(r'[Pp]assword:')
                child.sendline('CarrierRouter')
                child.expect(prompt)
                run(child, 'test "$(cat /run/vyos/boot-config-status)" = 0', prompt)

            def health(child, version):
                code = (
                    'from pathlib import Path; import subprocess,stat; '
                    'from vyos.system import image; '
                    f'assert image.get_running_image()=={version!r}; '
                    'assert all(stat.S_IMODE(Path(p).stat().st_mode)==0o755 '
                    'for p in ("/","/etc","/opt","/opt/vyatta","/opt/vyatta/etc","/var")); '
                    'assert all(Path(p).stat().st_uid==0 and '
                    'stat.S_IMODE(Path(p).stat().st_mode)==0o755 for p in '
                    '("/usr/bin/vyos-op-run", "/usr/libexec/vyos/op_mode/show_configuration_reveal.py")); '
                    'assert "cap_setuid=ep" in subprocess.check_output('
                    '["getcap","/usr/bin/vyos-op-run"],text=True); '
                    'assert subprocess.run(["runuser","-u","nobody","--",'
                    '"/usr/libexec/vyos/op_mode/show_configuration_reveal.py"],'
                    'capture_output=True).returncode!=0; '
                    'subprocess.run(["systemctl","is-active","--quiet","dbus"],check=True); '
                    'subprocess.run(["hostnamectl","--static"],check=True); '
                    'subprocess.run(["loginctl","--json=short","list-sessions","--no-pager"],check=True); '
                    'subprocess.run(["systemctl","is-active","--quiet","ssh@default"],check=True); '
                    'assert Path("/bin/carrier-cli").exists() and not Path("/bin/vbash").exists()')
                if args.check_arp_ignore:
                    code += ('; from vyos.config import Config; '
                             'assert Config().get_config_dict(["interfaces","ethernet","eth0"], '
                             'effective=True,get_first_key=True)["ip"]["arp"]["ignore"]=="2"; '
                             'assert Path("/proc/sys/net/ipv4/conf/eth0/arp_ignore").read_text().strip()=="2"')
                run(child, 'sudo python3 -c ' + shlex.quote(code), prompt)
                run(child, "sudo timeout 30 /bin/sh -c 'until ping -c 1 -W 1 10.0.2.2; do sleep 1; done'", prompt)

            child = spawn(True)
            try:
                child.expect(r'# ')
                run(child, 'while ! test -e /run/vyos/boot-config-status; do sleep 1; done; '
                           'test "$(cat /run/vyos/boot-config-status)" = 0', r'# ')
                setup = ('import os; from vyos.configsession import ConfigSession; '
                         's=ConfigSession(os.getpid()); '
                         's.set(["interfaces","ethernet","eth0","address"],value="dhcp"); '
                         's.set(["service","ssh","port"],value="2222"); '
                         's.commit(); s.save_config("/config/config.boot"); s._finalizer()')
                if args.check_arp_ignore:
                    setup = setup.replace('s.commit();',
                        's.set(["interfaces","ethernet","eth0","ip","arp","ignore"],value="2"); s.commit();')
                run(child, 'python3 -c ' + shlex.quote(setup), r'# ')
                child.sendline(f'umask 077; python3 {installer} --action install')
                for question, answer in (
                    ('Would you like to continue?', 'y'),
                    ('What would you like to name this image?', before),
                    ('Administrator account', ''),
                    ('Please enter a password for the "Carrier" administrator:', 'CarrierRouter'),
                    ('Please confirm password for the "Carrier" administrator:', 'CarrierRouter'),
                    ('What console should be used by default?', 'S'),
                    ('Which one should be used for installation?', ''),
                    ('Installation will delete all data on the drive. Continue?', 'y'),
                    ('Would you like to use all the free space on the drive?', 'y'),
                ):
                    child.expect_exact(question)
                    child.sendline(answer)
                child.expect_exact('The image installed successfully; please reboot now.', timeout=300)
                child.expect(r'# ')
                stop(child)
                print('PASS: actual installer completed under umask 077', flush=True)
            finally:
                child.close(force=True)

            child = spawn(False)
            try:
                login(child)
                health(child, before)
                print('PASS: installed GRUB boot, non-root login, D-Bus, hostname, SSH and network', flush=True)
                # CD -> persistent disk. Never stage this ISO in a guest tmpfs.
                run(child, 'sudo dd if=/dev/sr0 of=/config/qa-upgrade.iso bs=4M status=none', prompt)
                upgrade = f'umask 077; python3 {installer} --action add --no-prompt --image-path /config/qa-upgrade.iso'
                run(child, 'sudo /bin/bash -c ' + shlex.quote(upgrade), prompt, timeout=300)
                verify = ('from pathlib import Path; import stat; from vyos.system import disk,image; '
                          f'assert image.get_default_image(disk.find_persistence())=={args.version!r}; '
                          f'r=Path(disk.find_persistence())/"boot"/{args.version!r}/"rw"; '
                          'assert all(stat.S_IMODE((r/p).stat().st_mode)==0o755 '
                          'for p in ("","etc","opt","opt/vyatta","opt/vyatta/etc"))')
                run(child, 'sudo python3 -c ' + shlex.quote(verify), prompt)
                stop(child, sudo=True)
                print('PASS: actual image upgrade under umask 077; upper-root directory modes verified', flush=True)
            finally:
                child.close(force=True)

            child = spawn(False)
            try:
                login(child)
                health(child, args.version)
                # Real ACPI input through QEMU, not merely a config-file check.
                with socket.socket(socket.AF_UNIX) as qmp:
                    qmp.settimeout(5)
                    qmp.connect(str(root / 'qmp.sock'))
                    stream = qmp.makefile('rwb', buffering=0)
                    assert 'QMP' in json.loads(stream.readline())
                    for operation in ('qmp_capabilities', 'system_powerdown'):
                        stream.write((json.dumps({'execute': operation}) + '\n').encode())
                        while True:
                            response = json.loads(stream.readline())
                            if 'return' in response: break
                            assert 'error' not in response, response
                time.sleep(3)
                assert child.isalive(), 'ACPI short power event shut down the router'
                run(child, "sudo journalctl -b --no-pager -t carrier-power-key | grep -F 'ACPI power button ignored'", prompt)
                health(child, args.version)
                print('PASS: actual ACPI power key received and ignored; explicit poweroff still tested', flush=True)
                if args.check_migration:
                    migration = (
                        'import runpy; from vyos.configtree import ConfigTree; '
                        'm=runpy.run_path("/opt/vyatta/etc/config-migrate/migrate/bgp/1-to-2"); '
                        't=ConfigTree(""); b=["protocols","bgp"]; '
                        't.set(b+["system-as"],value="65001"); '
                        't.set(b+["peer-group","internal6","address-family","ipv6-unicast"]); '
                        't.set(b+["neighbor","2001:db8::2","peer-group"],value="internal6"); '
                        'old=t.to_json(); m["migrate"](t); m["migrate"](t); assert t.to_json()==old')
                    run(child, 'sudo python3 -c ' + shlex.quote(migration), prompt)
                    print('PASS: packaged BGP migration preserves IPv6-only group through repeated runs', flush=True)
                print('PASS: upgraded image booted from installed GRUB with healthy services; no source overlays', flush=True)
                stop(child, sudo=True)
            finally:
                child.close(force=True)


if __name__ == '__main__':
    main()
