#!/usr/bin/env python3
"""Fetch, verify and build the pinned SQLC plugin; stdout is protobuf only."""
import hashlib
import io
import os
from pathlib import Path
import shutil
import subprocess
import tarfile
from urllib.request import urlopen

revision = '40d1657be64a7fe2b07129e76a1328e42f3f0af2'
archive_hash = '750e66952638cf47b866fcd7288d47a6df9aa7f0fa0977e55a8ff5d9427377c8'
root = Path(__file__).resolve().parents[1]
patch = root / 'tools/sqlc-plugin-php-dbal/fixes.patch'
out = root / 'out/sqlc'
out.mkdir(parents=True, exist_ok=True)
checksum = archive_hash + hashlib.sha256(patch.read_bytes()).hexdigest()
binary = out / 'sqlc-gen-php'
marker = out / 'source.sha256'
if not binary.exists() or not marker.exists() or marker.read_text() != checksum:
    with urlopen(f'https://codeload.github.com/bharatvaj/sqlc-plugin-php-dbal/tar.gz/{revision}', timeout=60) as response:
        archive = response.read()
    if hashlib.sha256(archive).hexdigest() != archive_hash:
        raise RuntimeError('SQLC plugin source checksum mismatch')
    source = out / f'sqlc-plugin-php-dbal-{revision}'
    if source.exists():
        shutil.rmtree(source)
    with tarfile.open(fileobj=io.BytesIO(archive), mode='r:gz') as tar:
        tar.extractall(out)  # Only the checksum-verified, pinned archive is extracted.
    subprocess.run(['patch', '-s', '-p1', '-i', str(patch)], cwd=source, check=True)
    subprocess.run(['go', 'build', '-trimpath', '-o', str(binary), './plugin'], cwd=source, check=True)
    marker.write_text(checksum)
os.execv(binary, [str(binary)])
