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

root = Path(__file__).resolve().parents[1]
p = argparse.ArgumentParser()
p.add_argument('--fetch', action='store_true', help='Explicitly allow network fetching')
args = p.parse_args()
lock = json.loads((root / 'sources.lock').read_text())
for name, source in lock['sources'].items():
    destination = root / 'vendor' / name
    if not (destination / '.git').exists():
        if not args.fetch:
            sys.exit(f'Missing source {name}; rerun scripts/sources --fetch')
        destination.mkdir(parents=True, exist_ok=True)
        subprocess.run(['git', 'init', str(destination)], check=True)
        subprocess.run(['git', '-C', str(destination), 'remote', 'add', 'origin', source['url']], check=True)
        subprocess.run(['git', '-C', str(destination), 'fetch', '--depth', '1', 'origin', source['commit']], check=True)
        subprocess.run(['git', '-C', str(destination), 'checkout', '--detach', 'FETCH_HEAD'], check=True)
    actual = subprocess.check_output(['git', '-C', str(destination), 'rev-parse', 'HEAD'], text=True).strip()
    if actual != source['commit']:
        sys.exit(f'Wrong source revision: {name}: {actual}')
for filename, digest in lock['files'].items():
    path = root / filename
    if not path.is_file() or sha256(path) != digest:
        sys.exit(f'Missing or changed pinned input: {filename}')
print('Pinned revisions and firmware/toolchain hashes verified')
