#!/usr/bin/python3

# Some headers are generated at build time, so we ship them in pypy3 (anch-dep).
# Others are static and shipped in pypy3-dev (arch-indep).
# Because we are cherry-picking them from different places, verify that all the
# expected headers have been shipped.

import sys
from glob import glob
from os import listdir
from os.path import basename


def installed_headers(binpkg):
    path = f'debian/{binpkg}.install'
    with open(path, encoding='utf-8') as f:
        for line in f:
            if line.startswith('#'):
                continue
            parts = line.split()
            if len(parts) == 2:
                pattern, dest = parts
            elif len(parts) == 3 and parts[1] == '=>':
                pattern, _, dest = parts
            else:
                print(f'Failure to parse {path}: {line}')
                sys.exit(1)
            if dest.rstrip('/') == '/usr/include/pypy3.9':
                for fn in glob(pattern):
                    yield basename(fn)


installed = (
    set(installed_headers('pypy3-dev'))
    | set(installed_headers('pypy3')))
built_headers = set(
    basename(fn) for fn in listdir('include/pypy3.9')
    if fn.endswith('.h'))

if installed != built_headers:
    if built_headers - installed:
        print("Missing headers:", built_headers - installed)
    if installed - built_headers:
        print("Extra headers:", installed - built_headers)
    sys.exit(1)
