#!/usr/bin/env python
#
# Script to convert help files in the help/ directory to a single .sql file
# (C) 2001 Alex Badea <vampire@go.ro>
#

out_filename = "cservice.help.sql"
max_textlen = 8140

from os import listdir
from string import *

def prepare_dbtext(s):
	s = replace(s, "'", "\\'");
	s = replace(s, "\n", "\\n");
	s = replace(s, "\r", "\\r");
	return s

print "* Generating: %s" % out_filename
outf = open(out_filename, 'wt')
outf.write("-- This file was automatically generated by genhelp.py\n\n");
outf.write("DELETE FROM help;\n\n");

for language_id in listdir('help'):
	try:
		language_id = int(language_id)
	except:
		print "* Invalid language ID directory: %s" % language_id

		continue
	print "* Language ID: %d" % language_id
	
	outf.write("\n---------------------\n-- Language ID: %2d --\n---------------------\n\n" % language_id);
	
	for cmd in listdir('help/%d' % language_id):
		print "  %s" % cmd
		
		try:
			f = open('help/%d/%s' % (language_id, cmd), 'rt')
		except:
			print "* Cannot open %s" % cmd
			continue
		buf = prepare_dbtext(f.read(16777216))
		if len(buf) > max_textlen:
			print "* Topic too large (%d bytes) -- truncated to %d" % (len(buf), max_textlen)
			buf = buf[:max_textlen]
		outf.write("INSERT INTO help (language_id, topic, contents) VALUES (%d, '%s', '%s');\n" % \
			(language_id, prepare_dbtext(upper(cmd)), buf))
		f.close()

outf.close()
print "* Done"
