#!/usr/bin/env python3
import sys
sys.path.insert(0, "../")
from pykickstart.handlers import control
from pykickstart.version import DEVEL, stringToVersion, versionToString, \
    getVersionFromCommandClass


def _format_title(title):
    t = title.replace('|', ' or ')
    return "\n%s\n%s\n" % (t, '-' * len(t))

if __name__ == "__main__":
    handler_version = DEVEL
    if len(sys.argv) > 1:
        handler_version = stringToVersion(sys.argv[1])
    handler_string = versionToString(handler_version)

    # build a list of all possible commands, with their respective latest versions
    # tests/handlers.py guarantees we always have the latest
    # commands available in the commandMap, hence the latest
    # documentation as well.
    all_commands = {}
    for _version in control.commandMap:
        for command_name, command_class in control.commandMap[_version].items():
            command_version = getVersionFromCommandClass(command_class)
            command_version_string = versionToString(command_version)

            # we are building separately for RHEL and Fedora so don't
            # include commands which don't match
            if command_version_string.startswith('RHEL') and \
               not handler_string.startswith('RHEL'):
                continue

            # don't document command implementations which are newer
            # than the target we're building for
            if command_version > handler_version:
                continue

            if command_name not in all_commands:
                all_commands[command_name] = command_class
            else:
                # update our map with the latest possible versions
                last_version = getVersionFromCommandClass(all_commands[command_name])
                if command_version > last_version:
                    all_commands[command_name] = command_class

    # now loop over all commands and document them
    already_documented = []
    commands = list(all_commands.keys())
    commands.sort()
    for command_name in commands:
        command_class = all_commands[command_name]

        # some command classes respond to multiple commands
        # for example auth or authconfig, graphical or text
        # once documented we skip the next occurences in the map
        if command_class in already_documented:
            continue

        op = command_class()._getParser()
        print(_format_title(op.prog))
        op.print_help()
        already_documented.append(command_class)
