#!/usr/bin/env python3


import collections
import subprocess
import re


def run(*args):
    return subprocess.run(args, stdout=subprocess.PIPE).stdout.decode()

def info():
    info = dict()
    re_extension = re.compile(r'^(\w+):')
    re_function  = re.compile(r'^  (\w+):')
    lines = run('glewinfo')
    for line in lines.splitlines():
        match = re_extension.match(line)
        if match:
            extension = match.group(1)
            continue
        match = re_function.match(line)
        if match:
            info[match.group(1)] = extension
            continue
    return info

def compat(info):
    compat = collections.defaultdict(lambda: collections.defaultdict(list))
    lines = run('grep', '-RIon', '--exclude-dir=.git', '-E', r'\<gl[A-Z]\w+\>')
    for line in lines.splitlines():
        file, line_nr, function = line.split(':')
        location = f'{file}:{line_nr}'
        extension = info.get(function, 'NOT_FOUND')
        compat[extension][function].append(location)
    return compat

def report(compat, with_locations):
    for extension, functions in sorted(compat.items()):
        print(f'{extension}')
        for function, locations in sorted(functions.items()):
            print(f'  {function}')
            if with_locations:
                for location in locations:
                    print(f'    {location}')

def main():
    c = compat(info())
    report(c, False)
    print('')
    report(c, True)


if __name__ == '__main__':
    main()