#!/usr/bin/env python3

# Copyright © 2018 Jakub Wilk <jwilk@jwilk.net>
# SPDX-License-Identifier: MIT

import configparser
import functools
import glob
import io
import os
import re

here = os.path.dirname(__file__)
here = os.path.abspath(here)
root = here + '/..'

def main():
    os.chdir(root)
    cp = configparser.RawConfigParser()
    cp.read(here + '/layouts')
    layouts = cp['layouts']
    ext_to_fmt = {}
    layout_exts = {lname: set() for lname in layouts}
    for path in glob.iglob('*/Makefile'):
        fmt = os.path.dirname(path)
        with open(path, 'rt', encoding='UTF-8') as file:
            for line in file:
                match = re.match(r'^all:\s*(\S+)[.](\S+)$', line)
                if match is not None:
                    (lname, ext) = match.groups()
                    layout_exts[lname].add(ext)
                    ext_to_fmt[ext] = fmt
    file = io.StringIO()
    fprint = functools.partial(print, file=file, sep='')
    for lname, layout in layouts.items():
        descr, *layout = layout.strip().splitlines()
        fprint('* ', descr, '::')
        fprint()
        for line in layout:
            fprint('     ', line)
        fprint()
        for ext in sorted(layout_exts[lname]):
            line = '  `{fmt} <https://github.com/jwilk/traversal-archives/releases/download/0/{layout}.{ext}>`__'
            line = line.format(layout=lname, ext=ext, fmt=ext_to_fmt[ext])
            fprint(line)
        fprint()
    table = file.getvalue()
    file.close()
    with open('README', 'rt', encoding='UTF-8') as file:
        readme = [line.rstrip('\n') for line in file]
    m_begin = '.. automatically generated by .private/update-readme'
    m_end = '.. end of generated stuff'
    with open('README', 'wt', encoding='UTF-8') as file:
        fprint = functools.partial(print, file=file)
        ireadme = iter(readme)
        for line in ireadme:
            fprint(line)
            if line == m_begin:
                break
        fprint()
        fprint(table, end='')
        for line in ireadme:
            if line == m_end:
                fprint(line)
                break
        for line in ireadme:
            fprint(line)

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et
