#! /usr/bin/perl

#################################################################
# create_help.pl -- converts SGML docs to internal psql help
#
# Copyright 2000 by PostgreSQL Global Development Group
#
# $Header: /cvsroot/pgsql/src/bin/psql/create_help.pl,v 1.5 2000/03/01 21:09:58 petere Exp $
#################################################################

#
# This script automatically generates the help on SQL in psql from
# the SGML docs. So far the format of the docs was consistent
# enough that this worked, but this here is by no means an SGML
# parser.
#
# Call: perl create_help.pl sql_help.h
# The name of the header file doesn't matter to this script, but it
# sure does matter to the rest of the source.
#

$docdir = "./../../../doc/src/sgml/ref";
$outputfile = $ARGV[0] or die "$0: missing required argument\n";

$define = $outputfile;
$define =~ tr/a-z/A-Z/;
$define =~ s/\W/_/g;

opendir DIR, $docdir or die "$0: could not open documentation sources: $!\n";
open OUT, ">$outputfile" or die "$0: could not open output file '$outputfile': $!\n";

print OUT
"/*
 * *** Do not change this file. It is machine-generated. ***
 *
 * This file was generated by
 *     $^X $0 $outputfile
 * from the DocBook documentation in
 *     $docdir
 *
 */

#ifndef $define
#define $define

struct _helpStruct
{
    char	   *cmd;	   /* the command name */
    char	   *help;	   /* the help associated with it */
    char	   *syntax;	   /* the syntax associated with it */
};


static struct _helpStruct QL_HELP[] = {
";

$count = 0;

foreach $file (sort readdir DIR) {
    my ($cmdname, $cmddesc, $cmdsynopsis);
    $file =~ /\.sgml$/ || next;

    open FILE, "$docdir/$file" or next;
    $filecontent = join('', <FILE>);
    close FILE;

    $filecontent =~ m!<refmiscinfo>\s*SQL - Language Statements\s*</refmiscinfo>!i
	or next;

    $filecontent =~ m!<refname>\s*([a-z ]+?)\s*</refname>!i && ($cmdname = $1);
    $filecontent =~ m!<refpurpose>\s*(.+?)\s*</refpurpose>!i && ($cmddesc = $1);

    $filecontent =~ m!<synopsis>\s*(.+?)\s*</synopsis>!is && ($cmdsynopsis = $1);

    if ($cmdname && $cmddesc && $cmdsynopsis) {
        $cmdname =~ s/\"/\\"/g;

	$cmddesc =~ s/<\/?.+?>//sg;
	$cmddesc =~ s/\n/ /g;
        $cmddesc =~ s/\"/\\"/g;

	$cmdsynopsis =~ s/<\/?.+?>//sg;
	$cmdsynopsis =~ s/\n/\\n/g;
        $cmdsynopsis =~ s/\"/\\"/g;

	print OUT "    { \"$cmdname\",\n      \"$cmddesc\",\n      \"$cmdsynopsis\" },\n\n";
        $count++;
    }
    else {
	print STDERR "$0: parsing file '$file' failed at or near line $. (N='$cmdname' D='$cmddesc')\n";
    }
}

print OUT "
    { NULL, NULL, NULL }    /* End of list marker */
};


#define QL_HELP_COUNT $count


#endif /* $define */
";

close OUT;
closedir DIR;
