#!/usr/bin/env python
# encoding: utf8
#

#
# This must be run from the Wesnoth root directory.
#
# Run as:
#
# data/tools/about_cfg_to_wiki -w path_to_wesnoth_exe > about.wiki
#
# (-h option outputs help)

import sys, re, glob

import wesnoth.wmlparser2 as wmldata

def output(text):
    sys.stdout.write(text.encode("utf8"))

if __name__ == "__main__":
    import optparse

    option_parser = optparse.OptionParser()
    option_parser.add_option("-w", "--wesnoth",
        help="Specify the wesnoth executable to use.")
    options, args = option_parser.parse_args()

    files = ["data/core/about.cfg"]
    files.extend(glob.glob("data/campaigns/*/_main.cfg"))

    if not options.wesnoth:
        options.wesnoth = "./wesnoth"

    # Parse WML.
    class Section:
        def __init__(self, title):
            self.title = title
            self.lines = []

    chapters = []

    for arg in files:
        sections = []
        wml_parser = wmldata.Parser(options.wesnoth, None, None, False)
        wml_parser.parse_file(arg)
        wml = wml_parser
        if not wml.get_all(tag="about"):
            wml = wml.get_all(tag="campaign")
            if not wml or not wml[0].get_all(tag="about"):
                sys.stderr.write("No about section found in %s\n" % arg)
                continue
            wml = wml[0]
        for about in wml.get_all(tag="about"):
            section = Section(about.get_text_val("title"))
            for entry in about.get_all(tag="entry"):
                name = entry.get_text_val("name")
                comment = entry.get_text_val("comment", "")
                wikiuser = entry.get_text_val("wikiuser", "")
                email = entry.get_text_val("email", "")
                # Mask email names from spammers
                email = email.replace("@", "&#x40;").replace(".", "&#x2E;")
                # Interpret our local conventions for obfuscsting in SVN files
                email = email.replace("_AT_", "&#x40;").replace("_DOT_", "&#x2E;")
                section.lines.append((name, comment, wikiuser, email))
            if section.title:
                sections.append(section)
        chapters.append((arg, sections))

    # Output.
    output("""
{| style="float:right"
|
__TOC__
|}
__NOEDITSECTION__
In July 2003, '''David White''' released the first version of Wesnoth. Since
then, many people have joined the project, contributing in very different ways.

To make any changes to this list, please modify about.cfg in SVN or ask any
developer to do it for you.

""".lstrip())
    for path, sections in chapters:
        if path == "data/core/about.cfg":
            output("== Contributors ==\n")
        else:
            slash1 = path.rfind("/")
            slash2 = path.rfind("/", 0, slash1)
            beautified = path[slash2 + 1:slash1]
            beautified = beautified.replace("_", " ")
            beautified = beautified[0].upper() + beautified[1:]
            output("== %s ==\n" % beautified)
        for section in sections:
            output("=== %s ===\n" % section.title)
            for name, comment, wikiuser, email in section.lines:
                if name == "*":
                    output("<hr>\n")
                    continue
                if comment:
                    comment = " - " + comment
                if wikiuser:
                    # If a wiki user is given, the nickname is turned into a
                    # wiki link, or else the whole name.
                    if "(" in name:
                        name = re.sub(r"\((.*)\)", "([[User:%s|\\1]])" % wikiuser, name)
                    else:
                        # The whole name is turned into a link, but also an
                        # email is given - in this case add an extra link.
                        if email:
                            name += " ([[User:%s|%s]])" % (wikiuser, wikiuser)
                        else:
                            name = "[[User:%s|%s]]" % (wikiuser, name)
                if email:
                    if "(" in name:
                        name, nick = name.split("(", 1)
                        name = name.strip()
                        name = "[mailto:%s %s] (%s" % (email, name, nick)
                    else:
                        name = "[mailto:%s %s]" % (email, name)
                output("* %s%s\n" % (name, comment))

    output("""[[Category:Generated]]""")
