#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
import shutil
import sys
from policy import sha256

p = argparse.ArgumentParser(description='Archive existing evidence files, no device reads')
p.add_argument('--destination', type=Path, required=True)
p.add_argument('inputs', type=Path, nargs='+')
args = p.parse_args()
destination = args.destination.resolve()
if destination == Path('/mnt/storage') or Path('/mnt/storage') in destination.parents:
    sys.exit('Keep evidence off the experimental SD; archive on the development PC')
destination.mkdir(parents=True, exist_ok=False)
records = []
for index, source in enumerate(args.inputs):
    if not source.is_file():
        records.append(dict(source=str(source), status='missing'))
        continue
    target = destination / f'{index:02d}-{source.name}'
    shutil.copyfile(source, target)
    records.append(dict(source=str(source), artifact=target.name, sha256=sha256(target)))
(destination / 'manifest.json').write_text(json.dumps(records, indent=2) + '\n')
if any(r.get('status') == 'missing' for r in records):
    sys.exit('Some inputs were missing; see manifest.json')
