#!/usr/bin/env python3
"""Use the pinned D2 binary; installation and rendering never need the network."""
from pathlib import Path
import hashlib,os,platform,shutil,subprocess,sys,tarfile
root=Path(__file__).resolve().parents[1]
binary=os.environ.get('D2_BINARY') or os.environ.get('D2') or shutil.which('d2')
if not binary:
 if (platform.system(),platform.machine())!=('Darwin','arm64'):
  sys.exit('Install D2 v0.9.0 and set D2_BINARY=/absolute/path/to/d2 (no network during builds).')
 archive=root/'tools/vendor/d2-v0.9.0-macos-arm64.tar.gz'
 expected='eaf6c0c143e56dd9fa97bfb6df25ea9c1ebce40245f056a0768cf1a6c15d3064'
 if hashlib.sha256(archive.read_bytes()).hexdigest()!=expected:sys.exit('D2 release archive checksum mismatch')
 binary=root/'.cache/d2-v0.9.0/bin/d2'
 if not binary.is_file():
  binary.parent.mkdir(parents=True,exist_ok=True)
  with tarfile.open(archive) as source:
   member=source.extractfile('d2-v0.9.0/bin/d2')
   binary.write_bytes(member.read())
  binary.chmod(0o755)
version=subprocess.check_output([str(binary),'--version'],text=True).strip()
if version!='v0.9.0':sys.exit('Expected D2 v0.9.0; found '+version)
os.execv(str(binary),[str(binary)]+sys.argv[1:])
