#!/usr/bin/env python3

import subprocess
import glob
import pathlib
import shutil
import re
import base64


def generate_readme():
    # we rely on html comments in the markdown to process the file into
    # what we desire in the github pages content, generated by doxygen.
    # this is very simple and brittle.
    marker = re.compile(
        r"^<!-- (.*) \(this is used by the github pages export, don't modify!\) -->$")
    with open('README.md') as input, open('README.generated.md', 'w') as output:
        githubonly = False
        for line in input:
            if m := marker.match(line):
                directive = m.group(1).strip()
                print(f"got match {directive}")
                if directive == 'if(github) {':
                    assert not githubonly
                    githubonly = True
                elif directive == '}':
                    assert githubonly
                    githubonly = False
                elif directive.startswith('base64 '):
                    print(base64.b64decode(directive[7:]).decode(
                        "utf-8"), file=output)
                else:
                    raise Exception('failed to parse directive')

            if not githubonly:
                print(line, file=output)


def main():
    subprocess.run(['./scripts/prepare_doxygen.sh',])
    generate_readme()
    subprocess.run(['doxygen',])
    pathlib.Path('doc/api/html/doc').mkdir(parents=True, exist_ok=True)
    for file in glob.glob('doc/*png'):
        print(f"copying {file}")
        shutil.copy(file, 'doc/api/html/doc')


if __name__ == "__main__":
    main()
