#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
import shutil
import tempfile
from image import START, FAT_SIZE, normalize_fat_times, run, verify
from policy import sha256

p = argparse.ArgumentParser(description='Prepare explicit missing/corrupt payload test image files')
p.add_argument('source', type=Path)
p.add_argument('destination', type=Path)
p.add_argument('--mode', choices=['missing', 'corrupt'], required=True)
args = p.parse_args()
manifest = verify(args.source)
if manifest.get('negative_test'):
    raise SystemExit('Source must be a normal validated image')
if args.destination.exists():
    raise SystemExit('Destination already exists')
with tempfile.TemporaryDirectory(dir=args.destination.parent) as work:
    work = Path(work)
    disk, fat = work / 'disk.img', work / 'boot.fat'
    shutil.copyfile(args.source, disk)
    with disk.open('rb') as source:
        source.seek(START)
        fat.write_bytes(source.read(FAT_SIZE))
    if args.mode == 'corrupt':
        run('mcopy', '-i', fat, '::loader.img', work / 'loader.img')
        payload = bytearray((work / 'loader.img').read_bytes())
        payload[0] ^= 1
        (work / 'loader.img').write_bytes(payload)
        manifest['negative_sha256'] = sha256(work / 'loader.img')
    run('mdel', '-i', fat, '::loader.img')
    if args.mode == 'corrupt':
        run('mcopy', '-i', fat, work / 'loader.img', '::loader.img')
    manifest['negative_test'] = args.mode
    (work / 'manifest.json').write_text(json.dumps(manifest, sort_keys=True, indent=2) + '\n')
    run('mcopy', '-o', '-i', fat, work / 'manifest.json', '::manifest.json')
    normalize_fat_times(fat)
    with disk.open('r+b') as target:
        target.seek(START)
        target.write(fat.read_bytes())
    verify(disk)
    disk.rename(args.destination)
args.destination.with_suffix('.sha256').write_text(f'{sha256(args.destination)}  {args.destination.name}\n')
print(f'Validated {args.mode} negative test image; firmware must refuse its payload')
