#!/bin/env python
#
# @Copyright@
#  				Rocks(r)
#  		         www.rocksclusters.org
#  		         version 5.4 (Maverick)
#  
# Copyright (c) 2000 - 2010 The Regents of the University of California.
# All rights reserved.	
#  
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#  
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#  
# 2. Redistributions in binary form must reproduce the above copyright
# notice unmodified and in its entirety, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided 
# with the distribution.
#  
# 3. All advertising and press materials, printed or electronic, mentioning
# features or use of this software must display the following acknowledgement: 
#  
# 	"This product includes software developed by the Rocks(r)
# 	Cluster Group at the San Diego Supercomputer Center at the
# 	University of California, San Diego and its contributors."
# 
# 4. Except as permitted for the purposes of acknowledgment in paragraph 3,
# neither the name or logo of this software nor the names of its
# authors may be used to endorse or promote products derived from this
# software without specific prior written permission.  The name of the
# software includes the following terms, and any derivatives thereof:
# "Rocks", "Rocks Clusters", and "Avalanche Installer".  For licensing of 
# the associated name, interested parties should contact Technology 
# Transfer & Intellectual Property Services, University of California, 
# San Diego, 9500 Gilman Drive, Mail Code 0910, La Jolla, CA 92093-0910, 
# Ph: (858) 534-5815, FAX: (858) 534-7345, E-MAIL:invent@ucsd.edu
#  
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# @Copyright@
#
# $Log$
# Revision 1.3  2011/01/28 02:17:28  mjk
# Docbook cleanup (using Viz Roll as proto-type)
# - consistent entity naming (no more mixing of '-' and '_')
# - roll compat page only lists specified rolls (version.mk)
# - added note about using all OS cds with non-core rolls (e.g. viz)
# - added entities for roll names, and bools
# - logical styles used instead of direct formatting
#   e.g. constant vs. emphasis
# Works for Viz (needs new devel env installed)
# TODO: Update Base Roll to further standardize (slow)
# TODO: Cleanup all other Rolls (fast)
#
# Revision 1.2  2010/09/07 23:53:05  bruno
# star power for gb
#
# Revision 1.1  2010/06/22 21:07:44  mjk
# build env moving into base roll
#
# Revision 1.5  2009/05/01 19:07:15  mjk
# chimi con queso
#
# Revision 1.4  2008/10/18 00:56:07  mjk
# copyright 5.1
#
# Revision 1.3  2008/03/06 23:41:50  mjk
# copyright storm on
#
# Revision 1.2  2007/06/19 21:40:31  mjk
# do not use NAME in roll-profile.mk
#
# Revision 1.1  2007/06/16 01:37:58  mjk
# - better copyrights
# - added genrcldocs (gen rocks command line docs)
#

import os
import sys
import string

	
# create all the roll-<command>.sgml files

def docbook():
	for line in list:
		cmd  = 'stack %s help format=docbook' % line
		fout = 'roll-%s.sgml' % string.join(line.split(' '), '-')
		os.system('%s > %s' % (cmd, fout))

	# create the roll command chapter file
	
	prevVerb = ''
	file = open('roll-commands.sgml', 'w')
	file.write('<chapter id="roll-commands">\n')
	file.write('<title>Command Reference</title>\n\n')

	for line in list:
		currVerb = line.split(' ')[0]
		if currVerb != prevVerb:
			if prevVerb:
				file.write('</section>\n')
			file.write('\n<section id="command-%s"><title>%s</title>\n' % (currVerb, currVerb))
		file.write('&source-roll-%s;\n' % string.join(line.split(' '), '-'))
		prevVerb = currVerb

	if prevVerb:
		file.write('</section>\n')
	file.write('</chapter>\n')
	file.close()

def sphinx():
	try:
		os.mkdir('cli')
	except OSError:
		pass
	for line in list:
		cmd = 'stack %s help format=sphinx' % line
		f = '.'.join(line.split()) + '.rst'
		cmdline = '%s > cli/%s' % (cmd, f)
		print "Running %s" % cmdline
		os.system(cmdline)

	sphinxtoc()

def sphinxtoc():
	verblist = {}
	for line in list:
		l = line.split()
		verb = l[0]
		if not verblist.has_key(verb):
			verblist[verb] = []
		cmd = '.'.join(line.split())
		verblist[verb].append(cmd)
	
	print "Writing Sphinx TOC"
	for verb in verblist:
		verbfile = open('cli/%s.toc.rst' % verb, 'w')
		verbfile.write('%s\n' % verb)
		verbfile.write('='*len(verb) + '\n\n')
		verbfile.write('.. toctree::\n')
		verbfile.write('\t:maxdepth: 1\n\n')
		for cmd in verblist[verb]:
			verbfile.write('\t%s\n' % cmd)
		verbfile.close()


def markdoc():
	try:
		os.mkdir('cli')
	except OSError:
		pass
	cli_toc = {}
	# Generate documentation from each command
	for line in list:
		verb = line.split()[0]
		cmd = 'stack %s help format=md' % line
		f = '-'.join(line.split()) + '.md'
		try:
			os.mkdir('cli/%s' % verb)
		except OSError:
			pass
		cmdline = '%s > cli/%s/%s' % (cmd, verb, f)
		print "Running %s" % cmdline
		os.system(cmdline)

		# Keep a list of the verbs to
		# generate a TOC
		if not cli_toc.has_key(verb):
			cli_toc[verb] = []
		cli_toc[verb].append(line.split()[1:])


	# Generate Global / Comprehensive TOC File
	cli_toc_file = open('cli/CLI-documentation.md','w')
	cli_toc_file.write("# stacki Command Line Interface Reference\n\n")

	# Main Page Sidebar
	cli_sidebar = open('cli/_Sidebar.md','w')
	cli_sidebar.write('[Command Line Interface](CLI-documentation)\n\n')

	# Get a list of verbs
	verbs = cli_toc.keys()
	verbs.sort()
	for verb in verbs:
		# Verb-specific TOC files named <verb>-commands.md. 

		# Write each verb to the Global TOC and the main page
		cli_toc_file.write('* [%s](%s-commands)\n' % (verb, verb))
		# Connect the verb TOC file to the Main Sidebar
		cli_sidebar.write('* [%s](%s-commands)\n' % (verb, verb))

		# Create the verb TOC file
		print "Writing verbfile cli/%s/%s-commands.md" % (verb, verb)
		verbfile = open('cli/%s/%s-commands.md' % (verb, verb), 'w')
		# Title of verb TOC
		verbfile.write("# %s commands\n\n" % verb)

		# Verb specific Sidebar
		verb_sidebar = open('cli/%s/_Sidebar.md' % (verb), 'w')

		# Main Page Link
		verb_sidebar.write('[Command Line Interface](CLI-documentation)\n\n')

		# Get the current verb we're processing
		i = verbs.index(verb)

		# Add all the verbs before the current one to the sidebar
		non_exp_verbs = verbs[:i]
		for n in non_exp_verbs:
			verb_sidebar.write("* [%s](%s-commands)\n"% (n,n))

		# Current verb and its dependents in the sidebar
		verb_sidebar.write("* [%s](%s-commands)\n" % (verb, verb))
		for cli in cli_toc[verb]:
			# Get command name
			cmd = '%s %s' % (verb, ' '.join(cli).strip())
			# Get link
			if len(cli) > 0:
				lnk = '%s-%s' % (verb, '-'.join(cli).strip())
			else:
				lnk = '%s' % verb
			# Write the command to the Main TOC file
			cli_toc_file.write('  * [%s](%s)\n' % (cmd, lnk))
			# Write command to Verb TOC file
			verbfile.write('  * [%s](%s)\n' % (cmd, lnk))
			# Write command to Verb Sidebar
			verb_sidebar.write('  * [%s](%s)\n' % (cmd, lnk))

		# Add all verbs after the current verb in the sidebar
		non_exp_verbs = verbs[i+1:]
		for n in non_exp_verbs:
			verb_sidebar.write("* [%s](%s-commands)\n"% (n,n))
		verbfile.close()
		verb_sidebar.close()

	cli_toc_file.close()
		

def getCommands(roll=None):
	list	 = []
	if roll:
		isHeader = 1
		for line in os.popen('/opt/stack/bin/stack list pallet command %s' % roll).readlines():
			if isHeader:
				isHeader = 0
				continue
			list.append(line[:-1].strip())
	return list

roll     = sys.argv[1]
if roll == 'None':
	roll = None

list = getCommands(roll)

if len(sys.argv) > 2:
	fmt 	 = sys.argv[2]
else:
	fmt = 'docbook'

import __main__
f = getattr(__main__, fmt)
	

f()

