#!/usr/bin/python
#

# Copyright (C) 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""Script to generate documentation for remote API resources.

This is hard-coded to the section numbering we have in the master RST
document.

"""

import re
import cgi
import inspect

from ganeti.rapi import rlib2
from ganeti.rapi import connector


CHECKED_COMMANDS = ["GET", "POST", "PUT", "DELETE"]


def beautify(text):
  """A couple of small enhancements, epydoc-to-rst.

  """
  pairs = [
    ("@return:", "Returns:"),
    ]

  for old, new in pairs:
    text = text.replace(old, new)

  return text


def indent(text):
  """Returns a text block with all lines indented.

  """
  lines = text.splitlines()
  lines = ["  " + l for l in lines]
  return "\n".join(lines)


def main():
  # Get list of all resources
  all = list(connector.CONNECTOR.itervalues())

  # Sort rlib by URI
  all.sort(cmp=lambda a, b: cmp(a.DOC_URI, b.DOC_URI))

  print ".. Automatically generated, do not edit\n"

  for cls in all:
    title = cls.DOC_URI
    print "%s\n%s\n" % (title, "+" * len(title))

    # Class docstring
    description = inspect.getdoc(cls)
    if description:
      print "::\n"
      print indent(description.strip())
    print
    supported = [cmd for cmd in CHECKED_COMMANDS if hasattr(cls, cmd)]
    print "It supports the following commands: %s." % (", ".join(supported))
    print

    for cmd in CHECKED_COMMANDS:
      if not hasattr(cls, cmd):
        continue

      print "%s\n%s\n" % (cmd, "~" * len(cmd))

      # Get docstring
      text = inspect.getdoc(getattr(cls, cmd))
      if text:
        text = beautify(text)
        print "::\n"
        print indent(text)
        print


if __name__ == "__main__":
  main()