#!/usr/bin/env python3
"""Reject an ISO whose boot payload does not match its frozen rootfs."""
import argparse
import hashlib
import pathlib
import subprocess
import tempfile


def digest_file(path):
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def check_carrier_boot(squashfs):
    """Fail closed if the rolling archive silently replaces our patched fork."""
    status = subprocess.check_output(
        ['unsquashfs', '-cat', str(squashfs), 'var/lib/dpkg/status'], text=True)
    installed = {}
    for paragraph in status.split('\n\n'):
        fields = dict(line.split(': ', 1) for line in paragraph.splitlines()
                      if line and not line[0].isspace() and ': ' in line)
        if fields.get('Status') == 'install ok installed':
            installed[fields.get('Package')] = fields.get('Version')
    for name in ('live-boot', 'live-boot-initramfs-tools'):
        if installed.get(name) != '1:20151213.vyos1':
            raise ValueError(f'{name}: validated Carrier boot package missing; '
                             'restore pinned packages before publishing')
    print('PASS Carrier boot stack: pinned live-boot 1:20151213.vyos1')


def check_cli(squashfs, temp):
    """Stop a future image from silently falling back to the upstream 4.1 CLI."""
    def read(name):
        return subprocess.check_output(['unsquashfs', '-cat', str(squashfs), name], text=True)

    status = read('var/lib/dpkg/status')
    packages = {}
    for paragraph in status.split('\n\n'):
        fields = dict(line.split(': ', 1) for line in paragraph.splitlines()
                      if line and not line[0].isspace() and ': ' in line)
        if fields.get('Status') == 'install ok installed':
            packages[fields.get('Package')] = fields.get('Version')
    version = packages.get('vyatta-bash')
    if not version or subprocess.run(['dpkg', '--compare-versions', version, 'ge',
                                      '5.3.15-1+carrier2']).returncode:
        raise ValueError('Carrier CLI path migration missing: build scripts/package-build/carrier-bash first')
    listing = subprocess.check_output(['unsquashfs', '-ll', str(squashfs)], text=True)
    if any(line.rstrip().endswith(('/bin/vbash', '/usr/bin/vbash')) or
           '/bin/vbash ->' in line for line in listing.splitlines()):
        raise ValueError('Retired vbash executable or compatibility link remains in SquashFS')
    if not any(line.rstrip().endswith('/bin/carrier-cli') and line.startswith('-rwx')
               for line in listing.splitlines()):
        raise ValueError('Carrier CLI executable missing from actual SquashFS')
    for name in ('etc/passwd', 'etc/shells', 'etc/bash_completion.d/vyatta-op',
                 'etc/update-motd.d/99-reboot', 'opt/vyatta/etc/functions/script-template',
                 'opt/vyatta/bin/restricted-shell', 'opt/vyatta/bin/vyatta-op-cmd-wrapper',
                 'usr/libexec/vyos/op_mode/vyos-op-cmd-wrapper.sh',
                 'usr/libexec/vyos/conf_mode/system_login.py',
                 'usr/libexec/vyos/vyos-boot-config-loader.py'):
        contents = read(name)
        if '/bin/vbash' in contents or 'exec vbash' in contents:
            raise ValueError(f'Retired shell reference remains in {name}')
    if 'set enable-bracketed-paste on' not in read('etc/skel/.inputrc'):
        raise ValueError('New-account native paste setting missing')
    if "bind 'set enable-bracketed-paste on'" not in read('etc/bash_completion.d/vyatta-op'):
        raise ValueError('Existing-account native paste initialization missing')
    extracted = pathlib.Path(temp) / 'cli-capability'
    subprocess.run(['unsquashfs', '-quiet', '-no-progress', '-d', str(extracted),
                    str(squashfs), 'usr/bin/vyos-op-run'], check=True,
                   stdout=subprocess.DEVNULL)
    capability = subprocess.check_output(['getcap', str(extracted / 'usr/bin/vyos-op-run')], text=True)
    if 'cap_setuid=ep' not in capability:
        raise ValueError('Operator runner capability missing from actual SquashFS')
    print(f'PASS Carrier CLI {version}, no vbash path, migrated entry points, paste and operator capability')


def check_managed_ssh(squashfs, temp):
    """Carrier CLI must be the only automatic SSH listener configuration path."""
    extracted = pathlib.Path(temp) / 'ssh-policy'
    name = 'etc/systemd/system-generators/systemd-ssh-generator'
    subprocess.run(['unsquashfs', '-quiet', '-no-progress', '-d', str(extracted),
                    str(squashfs), name], check=True, stdout=subprocess.DEVNULL)
    mask = extracted / name
    if not mask.is_symlink() or str(mask.readlink()) != '/dev/null':
        raise ValueError('Carrier managed-SSH generator mask missing from actual SquashFS')
    print('PASS Carrier managed SSH: automatic VSOCK/UNIX generator masked')


def check_iso(iso, require_carrier_cli=False, require_managed_ssh=False,
              require_carrier_boot=False):
    # /tmp may be tmpfs on the build host. Extract the large rootfs alongside
    # the ISO instead of consuming RAM during artifact verification.
    with tempfile.TemporaryDirectory(prefix='check-boot-payload-', dir=iso.parent) as temp:
        live = pathlib.Path(temp) / 'live'
        subprocess.run(['xorriso', '-osirrox', 'on', '-indev', str(iso),
                        '-extract', '/live', str(live)], check=True,
                       stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        kernels = list(live.glob('vmlinuz-*'))
        if len(kernels) != 1:
            raise ValueError('Expected exactly one versioned kernel')
        version = kernels[0].name.removeprefix('vmlinuz-')
        for stem in ('vmlinuz', 'initrd.img'):
            name = f'{stem}-{version}'
            # Use a file rather than buffering the complete initramfs in RAM.
            payload = pathlib.Path(temp) / name
            with payload.open('wb') as stream:
                subprocess.run(['unsquashfs', '-cat',
                                str(live / 'filesystem.squashfs'),
                                f'boot/{name}'], stdout=stream, check=True)
            if not payload.stat().st_size:
                raise ValueError(f'Empty rootfs boot payload: {name}')
            expected = digest_file(payload)
            for filename in (name, stem):
                actual = digest_file(live / filename)
                if actual != expected:
                    raise ValueError(f'{filename}: ISO {actual} != rootfs {expected}')
            print(f'PASS {name} and {stem}: {expected}')
        if require_carrier_cli:
            check_cli(live / 'filesystem.squashfs', temp)
        if require_managed_ssh:
            check_managed_ssh(live / 'filesystem.squashfs', temp)
        if require_carrier_boot:
            check_carrier_boot(live / 'filesystem.squashfs')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('iso', type=pathlib.Path)
    parser.add_argument('--require-carrier-cli', action='store_true')
    parser.add_argument('--require-managed-ssh', action='store_true')
    parser.add_argument('--require-carrier-boot', action='store_true')
    args = parser.parse_args()
    check_iso(args.iso.resolve(), args.require_carrier_cli, args.require_managed_ssh,
              args.require_carrier_boot)
