#!/usr/bin/python3

# Copyright © 2012, 2013 Jakub Wilk <jwilk@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import io
import os
import re
import subprocess as ipc
import sys

import apt_pkg

def podify_reference(s):
    s = s.strip()
    s = re.sub(r'^([a-z]+://\S+)$', r'<I<\1>>', s)
    s = re.sub(r'^(.*)\((\d+)\)$', r'B<C<\1>>(\2)', s)
    return s

def podify_synopsis(s):
    if s.startswith(' '):
        s = s.lstrip()
        s = re.sub(r'<(.+?)>', r'I<\1>', s)
        s = re.sub(r'^(\S+)', r'B<\1>', s)
        s += '\n'
    return s

def podify_description(s):
    s = re.sub(r'^\s+', '', s, flags=re.MULTILINE)
    s = re.sub(r'<(.+?)>', r'I<\1>', s)
    return s

def fix_markup(s):
    # <http://bugs.debian.org/280148>:
    # manpage references should be rendered in bold, not in italics
    s = re.sub('L<(\w+)[(](\d)[)]>', r'B<C<\1>>(\2)', s)
    s = re.sub('L<([a-z]+://\S+)>', r'<I<\1>>', s)
    return s

def main():
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='UTF-8')
    base = os.path.join(os.path.dirname(__file__), os.pardir)
    desc_fn = os.path.join(base, 'doc', 'tags.desc')
    tmpl_fn = os.path.join(base, 'doc', 'adequate.podt')
    code_fn = os.path.join(base, 'adequate')
    with open(tmpl_fn, 'rt', encoding='UTF-8') as file:
        for line in file:
            line = line.rstrip()
            if line == '=head1 TAGS':
                output_tags(desc_fn)
            else:
                line = fix_markup(line)
                print(line)

def output_tags(desc_fn):
    print('=head1 TAGS')
    print()
    print('=over 4')
    print()
    with open(desc_fn, 'rt', encoding='UTF-8') as file:
        for section in apt_pkg.TagFile(file):
            tag = section['tag']
            print('=item B<C<{tag}>>'.format(tag=tag))
            print()
            try:
                description = section['description']
            except LookupError:
                pass
            else:
                description = podify_description(description)
                print(description)
                print()
            try:
                references = section['references']
            except LookupError:
                pass
            else:
                references = ', '.join(podify_reference(s) for s in references.splitlines())
                print('References: {refs}.'.format(refs=references))
                print()
    print('=back')

if __name__ == '__main__':
    main()

# vim:ts=4 sw=4 et
