#!/usr/bin/env python3

import os
import sys
import re

result = ''

with open('src/PROTOTYPES.c') as f:
  prototypes = f.read().splitlines()

with open('src/CHECKSUMS') as f:
  checksums = f.read().splitlines()

def porder(p):
  p = re.split(r'(\d+)',p)
  return [(1,int(x)) if x.isnumeric() else (0,x) for x in p]

for o in 'verify','decode','encode','sort','core','hashblocks','hash','kem':
  co = f'crypto_{o}'
  plist = sorted(os.listdir(co),key=porder)
  for p in plist:
    for checksum in checksums:
      if checksum.startswith(f'{co}/{p} '):
        if o in ('decode','encode') or (o == 'core' and 'inv' in p):
          checksum += ' nooverlap'
        result += checksum+'\n'
    macros = None
    for i in sorted(os.listdir(f'crypto_{o}/{p}')):
      with open(f'{co}/{p}/{i}/api.h') as f:
        imacros = f.read()
      if macros is None: macros = imacros
      assert macros == imacros
    result += macros.replace('CRYPTO_',f'{co}_{p}_')
  for fun in prototypes:
    fun = fun.strip()
    if re.search(f' {co}[(_]',fun):
      result += fun.replace('extern ','')
      result += '\n'

  result += '\n'

with open('api','w') as f:
  f.write(result)
