from pathlib import Path
import json
import shutil
import subprocess

base = Path('/work')
production = (base / 'RUN.NSH').read_text(encoding='utf-16')
target = json.loads((base / 'target.json').read_text())


def nsh(path, text):
    path.write_bytes(b'\xff\xfe' + text.replace('\r\n', '\n').replace('\n', '\r\n').encode('utf-16-le'))


def read_file(image, name):
    result = subprocess.run(['mtype', '-i', str(image), '::/' + name], capture_output=True)
    assert result.returncode == 0, result.stderr
    data = result.stdout
    return data.decode('utf-16' if data.startswith((b'\xff\xfe', b'\xfe\xff')) else 'utf-8', errors='replace')


def run_case(name, read_success=True, native=False, repeat=False):
    esp = base / ('qa4-' + name)
    image = base / ('qa4-' + name + '.img')
    if not repeat:
        (esp / 'EFI/BOOT').mkdir(parents=True)
        job = esp / 'EFI/UUID1117'
        job.mkdir()
        shutil.copyfile(base / 'SHELLX64.EFI', esp / 'EFI/BOOT/BOOTX64.EFI')
        shutil.copyfile(base / 'SHELLX64.EFI', job / 'SHELLX64.EFI')
        (job / 'HOST.ID').write_text('node-a')
        body = production.replace('@echo -off', '@echo -on').replace('fs0:\\EFI\\ubuntu\\shimx64.efi', 'fs0:\\FALLBACK.NSH')
        if native:
            shutil.copyfile(base / 'AMIDEEFIx64.EFI', job / 'AMIDEEFIx64.EFI')
        else:
            body = body.replace('AMIDEEFIx64.EFI', 'MOCK.NSH')
            nsh(job / 'MOCK.NSH', '@echo -off\necho CALL=%1 VALUE=%2 >> fs0:\\EFI\\UUID1117\\CALLS.TXT\nexit /b ' + ('0' if read_success else '42') + '\n')
        nsh(job / 'RUN.NSH', body)
        nsh(esp / 'FALLBACK.NSH', '@echo -off\necho FALLBACK_OK > fs0:\\FALLBACK.TXT\nreset -s\n')
        nsh(esp / 'startup.nsh', '@echo -off\nfs0:\nfs0:\\EFI\\UUID1117\\SHELLX64.EFI -nomap -noversion -nointerrupt -nostartup -exit fs0:\\EFI\\UUID1117\\RUN.NSH\necho CHILD_RETURNED > fs0:\\RETURN.TXT\nreset -s\n')
        with image.open('wb') as stream:
            stream.truncate(64 * 1024 * 1024)
        subprocess.run(['mkfs.vfat', '-F', '32', str(image)], check=True, capture_output=True)
        for item in esp.iterdir():
            subprocess.run(['mcopy', '-s', '-i', str(image), str(item), '::/'], check=True)
    job = esp / 'EFI/UUID1117'
    variables = base / (name + '-vars.fd')
    shutil.copyfile('/usr/share/OVMF/OVMF_VARS_4M.fd', variables)
    console = base / (name + ('-repeat' if repeat else '') + '-console.txt')
    command = ['qemu-system-x86_64', '-machine', 'q35,accel=tcg', '-cpu', 'qemu64', '-m', '256',
               '-drive', 'if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd',
               '-drive', 'if=pflash,format=raw,file=' + str(variables),
               '-drive', 'format=raw,file=' + str(image), '-display', 'none', '-monitor', 'none',
               '-serial', 'file:' + str(console), '-nic', 'none', '-no-reboot']
    result = subprocess.run(command, timeout=75, capture_output=True, text=True)
    (base / (name + '-qemu.txt')).write_text(result.stdout + result.stderr)
    assert result.returncode == 0, result.stderr
    assert 'FALLBACK_OK' in read_file(image, 'FALLBACK.TXT'), console.read_text(errors='replace')[-2000:]
    status = read_file(image, 'EFI/UUID1117/STATUS.TXT')
    if native:
        print('NATIVE_TOOL_RESULT', status.strip(), flush=True)
    else:
        calls = [line.strip() for line in read_file(image, 'EFI/UUID1117/CALLS.TXT').splitlines() if line.strip()]
        writes = [line for line in calls if target['new_raw_smbios_hex'] in line]
        if read_success:
            assert len(calls) == 3 and len(writes) == 1, calls
        else:
            assert len(calls) == 1 and len(writes) == 0 and 'WRITE_SKIPPED_READ_FAILED' in status, (calls, status)
        if repeat:
            assert 'ALREADY_ATTEMPTED' in status
    print('CASE_OK', name, 'repeat=' + str(repeat), flush=True)


run_case('success')
run_case('success', repeat=True)
run_case('read-failure', read_success=False)
run_case('native', native=True)
(base / 'qa-passed.txt').write_text('UEFI script success, duplicate guard, read-failure guard and native-tool return path passed.\n')
