#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2012,2013,2014,2015,2017  Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import os
import sys
import argparse
from collections import defaultdict

try:
    import ms.version
except ImportError:
    pass
else:
    ms.version.addpkg('lxml', '3.2.5')

from lxml import etree

was_error = False


def error(message):
    global was_error

    print("ERROR: %s" % message, file=sys.stderr)
    was_error = True


def read_docbook(file, commands):
    cmd, xml = os.path.splitext(os.path.basename(file))

    try:
        tree = etree.parse(file)
    except etree.XMLSyntaxError as err:
        error("Failed to parse %s: %s" % (file, err))
        return

    tree.xinclude()

    # This code is somewhat depends on the style the existing documentation is
    # written. If the style changes considerably, then the code may need to be
    # adapted.
    ns = "http://docbook.org/ns/docbook"
    refsynopsisdiv = tree.find("{%s}refsynopsisdiv" % ns)
    if refsynopsisdiv is None:
        error("No refsynopsisdiv in %s. Maybe namespace is wrong?" % file)

    commands[cmd] = defaultdict(dict)

    # Collect all options mentioned in the synopsis
    # TODO: use xpath?
    for section in refsynopsisdiv.findall("{%s}cmdsynopsis" % ns):
        for option in section.getiterator("{%s}option" % ns):
            optname = option.text.strip()
            commands[cmd][optname]["docbook"] = True
            if option.findall("{%s}replaceable" % ns):
                commands[cmd][optname]["synopsis_has_arg"] = True

    # Collect all options described in a refsect1 titled "Options"
    # TODO: use xpath?
    for section in tree.findall("{%s}refsect1" % ns):
        title = section.find("{%s}title" % ns)
        if title.text.strip().lower() != "options":
            continue

        # Look for varlistentry/term/option
        # TODO: use xpath?
        for varentry in section.getiterator("{%s}varlistentry" % ns):
            term = varentry.find("{%s}term" % ns)
            for option in term.getiterator("{%s}option" % ns):
                optname = option.text.strip()