#!/usr/bin/env python3
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import runpy
import tarfile
import tempfile

def main():
    p=argparse.ArgumentParser(description='Read-only eth0 evidence. No MMIO, PHY writes or link changes.')
    p.add_argument('--output',required=True,type=Path)
    a=p.parse_args();output=a.output.resolve()
    if output.exists():raise SystemExit('Output already exists')
    if not output.parent.is_dir():raise SystemExit('Create the destination directory on eMMC or RAM first')
    mount=json.loads(subprocess.check_output(['findmnt','-J','-o','SOURCE,FSTYPE,MAJ:MIN,OPTIONS','-T',str(output.parent)],text=True))['filesystems'][0]
    if mount['fstype']=='overlay':
        writer=runpy.run_path(str(Path(__file__).with_name('flash-sd')))
        devices=json.loads(subprocess.check_output(['lsblk','-J','-b','-p','-o','NAME,TYPE,MAJ:MIN,FSTYPE,UUID'],text=True))
        flat=[]
        def walk(node,parents):
            flat.append((node,parents))
            for child in node.get('children',[]):walk(child,parents+[node['name']])
        for node in devices['blockdevices']:walk(node,[])
        writer['r5s_overlay_backing'](mount,flat)
    elif mount['fstype'] not in ('tmpfs','ramfs'):
        raise SystemExit('Use verified R5S eMMC root overlay or RAM destination')
    model=Path('/sys/firmware/devicetree/base/model').read_bytes().rstrip(b'\0')
    compatible=Path('/sys/firmware/devicetree/base/compatible').read_bytes().split(b'\0')
    if model!=b'FriendlyElec NanoPi R5S' or b'friendlyelec,nanopi-r5s' not in compatible or b'rockchip,rk3568' not in compatible:raise SystemExit('Unsupported board')
    with tempfile.TemporaryDirectory(dir=output.parent,prefix='gmac-evidence-') as temp:
        dest=Path(temp);meta=dict(model=model.decode(),destination_mount=mount,original_fdt=False)
        for name,path in [('cmdline','/proc/cmdline'),('iomem','/proc/iomem'),('mountinfo','/proc/self/mountinfo')]:
            (dest/name).write_bytes(Path(path).read_bytes())
        fdt=Path('/sys/firmware/fdt')
        if fdt.exists():shutil.copyfile(fdt,dest/'runtime-original.dtb');meta['original_fdt']=True
        shutil.copytree('/sys/firmware/devicetree/base',dest/'live-tree')
        if shutil.which('dtc'):
            result=subprocess.run(['dtc','-I','fs','-O','dtb','-o',str(dest/'runtime-reconstructed.dtb'),'/sys/firmware/devicetree/base'],capture_output=True)
            (dest/'dtc.log').write_bytes(result.stdout+result.stderr)
            meta['reconstructed_returncode']=result.returncode
        meta['links']={}
        for name in ('device','device/driver','device/of_node','phydev'):
            path=Path('/sys/class/net/eth0')/name
            meta['links'][name]=str(path.resolve()) if path.exists() else None
        mdio=dest/'mdio';mdio.mkdir()
        for dev in Path('/sys/bus/mdio_bus/devices').glob('*'):
            for name in ('phy_id','phy_interface','modalias','uevent'):
                path=dev/name
                if path.is_file():(mdio/(dev.name+'-'+name)).write_bytes(path.read_bytes())
        for args,label in [(['ethtool','-i','eth0'],'driver'),(['ethtool','eth0'],'link')]:
            if shutil.which('ethtool'):
                result=subprocess.run(args,capture_output=True,timeout=10)
                (dest/(label+'.txt')).write_bytes(result.stdout+result.stderr);meta[label+'_returncode']=result.returncode
            else:meta[label+'_returncode']='ethtool unavailable; not installed automatically'
        (dest/'metadata.json').write_text(json.dumps(meta,indent=2)+'\n')
        (dest/'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(f.read_bytes()).hexdigest()}  {f.relative_to(dest)}\n' for f in sorted(dest.rglob('*')) if f.is_file()))
        with output.open('xb') as stream,tarfile.open(fileobj=stream,mode='w:gz') as archive:archive.add(dest,arcname='gmac-evidence')
    print(output,hashlib.sha256(output.read_bytes()).hexdigest())
if __name__=='__main__':main()
