#!/usr/bin/env python3
"""Set up an empty Ubuntu base, then review a public GitHub repository in a copy.

  python3 qemu-review-vm.py setup
  python3 qemu-review-vm.py review https://github.com/OWNER/REPO
  python3 qemu-review-vm.py remove

The base defaults to ~/review-vm; put --state PATH before the action to change it.
Review opens an isolated SSH shell. An optional command string after -- runs in
that same isolated guest. Exiting removes the disposable copy. Nothing from the
repository is mounted, checked out, or executed on the host.
"""
import argparse
from contextlib import contextmanager
import fcntl
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import uuid

FORMAT = 'qemu-review-vm-v2'
IMAGE_BASE = 'https://cloud-images.ubuntu.com/releases/noble/release/'
SSH_PORT = 2222


class Failure(Exception):
    pass


def require(condition, message):
    if not condition:
        raise Failure(message)


def write(path, value):
    require(not path.is_symlink(), f'Refusing symlink: {path}')
    path.write_text(value if isinstance(value, str) else json.dumps(value, indent=2) + '\n')
    path.chmod(0o600)


def safe_text(value):
    # Logs are inspectable text, never terminal control sequences from a guest.
    return ''.join(c if c in '\n\t' or ' ' <= c <= '~' else f'\\u{ord(c):04x}' for c in value)


def run(args, **kwargs):
    return subprocess.run([str(arg) for arg in args], check=True, **kwargs)


def state_path(path):
    path = path.expanduser()
    require(not path.is_symlink(), 'Use a state path that is not a symlink.')
    path = path.resolve()
    require(path != Path('/') and not any(c in str(path) for c in ',\r\n'),
            'Use a state path without commas or newlines.')
    return path


def assert_off(path):
    pidfile = path / 'vm.pid'
    if pidfile.exists():
        pid = int(pidfile.read_text())
        require(pid > 0, 'Invalid VM PID file; inspect the state directory.')
        try:
            os.kill(pid, 0)
        except ProcessLookupError:
            return
        raise Failure(f'VM PID {pid} may still be running. Refusing to copy or delete its disk: {path}')


@contextmanager
def owned_state(path, create=False):
    if create:
        require(not path.exists(), 'State already exists. Choose another --state, or remove the old base first.')
        path.mkdir(mode=0o700, parents=True, exist_ok=False)
        write(path / 'owner.json', {'format': FORMAT, 'path': str(path)})
    require(path.is_dir() and path.stat().st_uid == os.getuid() and path.stat().st_mode & 0o077 == 0,
            'State must be a private directory owned by you. Run setup first.')
    require(not any(p.is_symlink() for p in path.iterdir()), 'Symlinks are not allowed in the base directory.')
    owner = json.loads((path / 'owner.json').read_text())
    require(owner == {'format': FORMAT, 'path': str(path)}, 'This is not a base owned by this helper.')
    with (path / '.lock').open('a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise Failure('Another setup, review, or removal is using this base.')
        assert_off(path)
        for copy in path.glob('review-*'):
            assert_off(copy)
        yield


def discover():
    system, machine = platform.system(), platform.machine().lower()
    arch = {'arm64': 'arm64', 'aarch64': 'arm64', 'x86_64': 'amd64', 'amd64': 'amd64'}.get(machine)
    require(system in ('Darwin', 'Linux') and arch, 'Supported hosts: macOS/Linux on ARM64 or x86_64.')
    qemu = 'qemu-system-aarch64' if arch == 'arm64' else 'qemu-system-x86_64'
    for name in (qemu, 'qemu-img', 'ssh', 'ssh-keygen', 'curl'):
        require(shutil.which(name), f'Missing {name}; install the documented host prerequisites first.')
    accel = 'hvf' if system == 'Darwin' else 'kvm'
    require(accel in run([qemu, '-accel', 'help'], capture_output=True, text=True).stdout,
            f'QEMU does not support {accel}; hardware acceleration is required.')
    require(system != 'Linux' or os.access('/dev/kvm', os.R_OK | os.W_OK),
            'KVM is unavailable or inaccessible. Enable virtualization and /dev/kvm permissions.')
    roots = [Path(shutil.which(qemu)).resolve().parent.parent / 'share/qemu'] + [
        Path(p) for p in ['/usr/share/AAVMF', '/usr/share/OVMF', '/usr/share/qemu',
                          '/usr/share/edk2/aarch64', '/usr/share/edk2/ovmf']]
    if system == 'Darwin':
        iso = ['hdiutil']
    else:
        iso = ['genisoimage'] if shutil.which('genisoimage') else ['xorriso', '-as', 'mkisofs']
    require(shutil.which(iso[0]), 'Install genisoimage or xorriso for the cloud-init seed.')
    pairs = ([('edk2-aarch64-code.fd', 'edk2-arm-vars.fd'), ('AAVMF_CODE.fd', 'AAVMF_VARS.fd'),
              ('QEMU_EFI-pflash.raw', 'vars-template-pflash.raw')] if arch == 'arm64' else
             [('edk2-x86_64-code.fd', 'edk2-i386-vars.fd'), ('OVMF_CODE_4M.fd', 'OVMF_VARS_4M.fd'),
              ('OVMF_CODE.fd', 'OVMF_VARS.fd')])
    firmware = next(((root / code, root / variables) for root in roots for code, variables in pairs
                     if (root / code).is_file() and (root / variables).is_file()), None)
    require(firmware, 'Matching UEFI firmware not found; install qemu-efi-aarch64 or ovmf on Linux.')
    return dict(system=system, arch=arch, qemu=shutil.which(qemu), accel=accel, iso=iso,
                firmware_code=str(firmware[0]), firmware_vars=str(firmware[1]))


class Guest:
    def __init__(self, path, config, mac, logs):
        self.path, self.config, self.mac, self.logs = path, config, mac, logs
        self.process = None
        self.boots = 0

    def start(self, isolated=False, seed=False):
        require(self.process is None, 'Stop the guest before changing its network.')
        (self.path / 'vm.pid').unlink(missing_ok=True)
        cfg = self.config
        self.boots += 1
        self.serial = self.logs / f'serial-{self.boots}.log'
        # Boot from disk; minimal Linux QEMU packages may omit the NIC's PXE ROM.
        args = [cfg['qemu'], '-name', 'repo-review', '-machine', 'virt' if cfg['arch'] == 'arm64' else 'q35',
                '-accel', cfg['accel'], '-cpu', 'host', '-smp', '2', '-m', '4096',
                '-drive', 'if=pflash,format=raw,readonly=on,file=' + cfg['firmware_code'],
                '-drive', f'if=pflash,format=raw,file={self.path}/vars.fd',
                '-drive', f'if=virtio,format=qcow2,file={self.path}/vm.qcow2',
                '-netdev', f'user,id=net0,ipv6=off,restrict={"on" if isolated else "off"},hostfwd=tcp:127.0.0.1:{SSH_PORT}-:22',
                '-device', f'virtio-net-pci,netdev=net0,mac={self.mac},romfile=', '-display', 'none', '-monitor', 'none',
                '-serial', f'file:{self.serial}', '-pidfile', str(self.path / 'vm.pid')]
        if seed:
            args += ['-drive', f'if=virtio,format=raw,readonly=on,file={self.path}/seed.iso']
        with (self.logs / 'qemu.log').open('ab') as log:
            self.process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
        print('Booting', 'isolated' if isolated else 'online', flush=True)
        self.wait()

    def ssh(self, admin=False):
        return ['ssh', '-F', 'none', '-a', '-x', '-o', 'IdentitiesOnly=yes', '-o', 'BatchMode=yes',
                '-o', 'StrictHostKeyChecking=yes', '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'ConnectTimeout=5',
                '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4',
                '-o', f'UserKnownHostsFile={self.path}/known_hosts', '-i', str(self.path / 'identity'),
                '-p', str(SSH_PORT), ('setupadmin' if admin else 'review') + '@127.0.0.1']

    def remote(self, command, admin=False, timeout=120, log=None):
        result = subprocess.run(self.ssh(admin) + [command], text=True, capture_output=True, timeout=timeout)
        if log:
            write(self.logs / log, safe_text(result.stdout + result.stderr))
            require(result.returncode == 0, f'Guest operation failed; see {self.logs / log}')
        return result

    def wait(self):
        deadline = time.monotonic() + 600
        while time.monotonic() < deadline:
            require(self.process.poll() is None, f'QEMU exited. See {self.logs / "qemu.log"}')
            try:
                if self.remote('true', timeout=10).returncode == 0:
                    return
            except subprocess.TimeoutExpired:
                pass
            time.sleep(2)
        raise Failure(f'Timed out waiting for pinned SSH. See {self.logs}')

    def stop(self):
        if self.process is None:
            return
        if self.process.poll() is None:
            print('Shutting down guest...', flush=True)
            try:
                self.remote('sudo systemctl poweroff', admin=True, timeout=30)
            except subprocess.TimeoutExpired:
                pass
            try:
                self.process.wait(timeout=120)
            except subprocess.TimeoutExpired:
                raise Failure(f'Graceful shutdown timed out. PID {self.process.pid} and disk retained at {self.path}')
        self.process = None
        (self.path / 'vm.pid').unlink(missing_ok=True)

    def discard(self):
        # The disk is about to be deleted, so there is nothing to shut down cleanly.
        if self.process is None:
            return
        self.process.kill()
        try:
            self.process.wait(timeout=30)
        except subprocess.TimeoutExpired:
            raise Failure(f'QEMU PID {self.process.pid} did not exit. Its files are kept at {self.path}')
        self.process = None


def make_base(path, config, mac):
    image = f'ubuntu-24.04-server-cloudimg-{config["arch"]}.img'
    for name, remote in [('SHA256SUMS', 'SHA256SUMS'), ('source.img', image)]:
        print('Downloading', remote, flush=True)
        # Fail only when the download stalls below 1 KB/s for five minutes.
        run(['curl', '--fail', '--location', '--retry', '3', '--connect-timeout', '30',
             '--speed-limit', '1024', '--speed-time', '300', '--proto', '=https', '--tlsv1.2',
             '--progress-bar' if name == 'source.img' else '--silent', '--show-error',
             '--output', path / name, IMAGE_BASE + remote])
    sums = [line.split() for line in (path / 'SHA256SUMS').read_text().splitlines()]
    expected = next((fields[0] for fields in sums if len(fields) == 2 and fields[1].lstrip('*') == image), None)
    require(expected, f'{image} is not listed in SHA256SUMS.')
    with (path / 'source.img').open('rb') as source:
        digest = hashlib.sha256()
        for block in iter(lambda: source.read(4 * 1024 * 1024), b''):
            digest.update(block)
    require(digest.hexdigest() == expected, 'Ubuntu image checksum mismatch. Do not boot.')
    copy_disk(path / 'source.img', path / 'vm.qcow2')
    run(['qemu-img', 'resize', path / 'vm.qcow2', '30G'])
    (path / 'source.img').unlink()
    shutil.copyfile(config['firmware_vars'], path / 'vars.fd')
    for key in ('identity', 'host_key'):
        run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', '', '-f', path / key])
    host_private = (path / 'host_key').read_text()
    host_public = (path / 'host_key.pub').read_text().strip()
    for name in ('host_key', 'host_key.pub'):
        (path / name).unlink()
    write(path / 'known_hosts', f'[127.0.0.1]:{SSH_PORT} {host_public}\n')
    seed = path / 'seed'
    seed.mkdir(mode=0o700)
    write(seed / 'meta-data', f'instance-id: {uuid.uuid4().hex}\nlocal-hostname: repo-review\n')
    write(seed / 'network-config', f'version: 2\nethernets:\n  nic:\n    match:\n      macaddress: "{mac}"\n    dhcp4: true\n')
    public_key = (path / 'identity.pub').read_text().strip()
    users = ''
    for name in ('setupadmin', 'review'):
        users += f'  - name: {name}\n    lock_passwd: true\n    shell: /bin/bash\n'
        users += '    sudo: ALL=(ALL) NOPASSWD:ALL\n    groups: [sudo]\n' if name == 'setupadmin' else '    sudo: null\n'
        users += f'    ssh_authorized_keys:\n      - {public_key}\n'
    host_key = ''.join(f'    {line}\n' for line in host_private.splitlines())
    write(seed / 'user-data', '#cloud-config\ndisable_root: true\nssh_pwauth: false\n'
          f'ssh_keys:\n  ed25519_private: |\n{host_key}  ed25519_public: {host_public}\nusers:\n' + users)
    if config['system'] == 'Darwin':
        run(['hdiutil', 'makehybrid', '-iso', '-joliet', '-default-volume-name', 'CIDATA', '-o', path / 'seed.iso', seed])
    else:
        run(config['iso'] + ['-quiet', '-V', 'CIDATA', '-J', '-R', '-o', str(path / 'seed.iso'), str(seed)])


def copy_disk(source, destination):
    run(['qemu-img', 'convert', '-O', 'qcow2', source, destination])


def provision(guest):
    result = guest.remote('sudo cloud-init status --wait --format json', True, 1800, 'cloud-init.log')
    status = json.loads(result.stdout)
    require(status.get('status') == 'done' and not status.get('errors') and not status.get('recoverable_errors'),
            'Cloud-init did not finish cleanly. Inspect cloud-init.log.')
    print('Applying Ubuntu updates...', flush=True)
    guest.remote('sudo apt-get -o APT::Update::Error-Mode=any update && '
                 'sudo DEBIAN_FRONTEND=noninteractive apt-get install -y git openssh-server && '
                 'sudo DEBIAN_FRONTEND=noninteractive apt-get -o APT::Get::Always-Include-Phased-Updates=true dist-upgrade -y',
                 True, None, 'updates.log')
    guest.stop()
    guest.start(seed=True)
    guest.remote('set -e; test ! -e /run/reboot-required; '
                 'test -z "$(apt list --upgradable 2>/dev/null | tail -n +2)"; '
                 'test "$(id -u review)" -ne 0; test "$(id -Gn review)" = review; '
                 'test "$(sudo passwd -S review | cut -d " " -f2)" = L; '
                 'test "$(sudo passwd -S root | cut -d " " -f2)" = L; '
                 'sudo -u review sudo -n true && exit 1; '
                 'git --version; systemctl is-active ssh', True, 300, 'verified.log')
    guest.remote('sudo touch /etc/cloud/cloud-init.disabled', True, log='disable-cloud-init.log')


def setup(path):
    config = discover()
    with owned_state(path, create=True):
        logs = path / 'logs'
        logs.mkdir(mode=0o700)
        mac = '52:54:00:' + ':'.join(uuid.uuid4().hex[i:i + 2] for i in (0, 2, 4))
        make_base(path, config, mac)
        guest = Guest(path, config, mac, logs)
        try:
            guest.start(seed=True)
            provision(guest)
        finally:
            guest.stop()
        (path / 'seed.iso').unlink()
        shutil.rmtree(path / 'seed')
        write(path / 'base.json', dict(format=FORMAT, config=config, mac=mac))
    print(f'Setup complete. Empty base is powered off at {path}')


def github_url(value):
    match = re.fullmatch(r'https://github\.com/([A-Za-z0-9][A-Za-z0-9-]{0,38})/([A-Za-z0-9_.-]{1,100})/?', value)
    require(match and match[2] not in ('.', '..'), 'Use a public HTTPS GitHub URL: https://github.com/OWNER/REPO')
    repo = match[2].removesuffix('.git')
    require(repo and repo not in ('.', '..'), 'Invalid repository name.')
    return f'https://github.com/{match[1]}/{repo}.git'


def review(path, url, command):
    url = github_url(url)
    with owned_state(path):
        base = json.loads((path / 'base.json').read_text())
        require(base.get('format') == FORMAT, 'Setup is incomplete; remove this base and run setup again.')
        logs = path / 'sessions' / uuid.uuid4().hex[:8]
        logs.mkdir(mode=0o700, parents=True)
        temporary = Path(tempfile.mkdtemp(prefix='review-', dir=path))
        guest = Guest(temporary, base['config'], base['mac'], logs)
        print(f'Review logs: {logs}', flush=True)
        try:
            copy_disk(path / 'vm.qcow2', temporary / 'vm.qcow2')
            for name in ('vars.fd', 'identity', 'known_hosts'):
                shutil.copyfile(path / name, temporary / name)
            guest.start()
            git = ('env -i HOME=/home/review PATH=/usr/bin:/bin GIT_CONFIG_NOSYSTEM=1 '
                   'GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0 git '
                   '-c core.hooksPath=/dev/null -c core.fsmonitor=false -c submodule.recurse=false '
                   '-c credential.helper= -c protocol.allow=never -c protocol.https.allow=always '
                   '-c http.lowSpeedLimit=1024 -c http.lowSpeedTime=300 ')
            guest.remote(git + 'clone --no-checkout --template= -- ' + shlex.quote(url) + ' /home/review/repository',
                         timeout=None, log='clone.log')
            commit = guest.remote(git + '-C /home/review/repository rev-parse --verify HEAD', log='commit.log').stdout.strip()
            require(re.fullmatch(r'[0-9a-f]{40}|[0-9a-f]{64}', commit), 'Git did not return a valid commit ID.')
            guest.stop()
            guest.start(isolated=True)
            guest.remote(git + '-C /home/review/repository checkout --force --detach ' + commit, log='checkout.log')
            print(f'Restricted networking enabled. Reviewing {url} at {commit}. Exit to discard this VM.', flush=True)
            remote = 'cd /home/review/repository && ' + (command if command is not None else 'exec /bin/bash --noprofile --norc')
            ssh = guest.ssh()
            if command is None:
                ssh.insert(1, '-tt')
            return subprocess.call(ssh + [remote])
        finally:
            # discard() raises if QEMU is still running, so a live disk is never deleted.
            guest.discard()
            shutil.rmtree(temporary)
            for log in logs.glob('serial-*.log'):
                write(log, safe_text(log.read_text(errors='replace')))
            print('Discarded review VM.', flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--state', type=Path, default=Path.home() / 'review-vm', help='base directory (default: ~/review-vm)')
    actions = parser.add_subparsers(dest='action', required=True)
    actions.add_parser('setup', help='create the empty base')
    action = actions.add_parser('review', help='review a public GitHub repository')
    action.add_argument('url', help='https://github.com/OWNER/REPO')
    action.add_argument('command', nargs='?', help='optional guest shell command after --')
    actions.add_parser('remove', help='delete this helper\'s powered-off base and logs')
    args = parser.parse_args()
    require(os.geteuid() != 0, 'Run as an ordinary user; install host prerequisites separately.')
    os.umask(0o077)
    path = state_path(args.state)
    if args.action == 'setup':
        setup(path)
    elif args.action == 'review':
        return review(path, args.url, args.command)
    else:
        with owned_state(path):
            shutil.rmtree(path)
        print('Removed owned base:', path)
    return 0


if __name__ == '__main__':
    def interrupted(signum, frame):
        raise KeyboardInterrupt

    signal.signal(signal.SIGTERM, interrupted)
    signal.signal(signal.SIGHUP, interrupted)
    try:
        sys.exit(main())
    except (Failure, subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError, ValueError, KeyboardInterrupt) as error:
        print('ERROR:', safe_text(str(error)) or 'Interrupted.', file=sys.stderr)
        sys.exit(1)
