#!/usr/bin/perl

#
# This script should be pulling the info from the IntParams table instead
#

use Getopt::Long;
use Mysql;

use Env qw(LSBUSER LSBDBPASSWD LSBDB LSBDBHOST);

sub
usage()
{
die "mkfuncprototype -h <headername>";
}

# Uncomment to trace SQL statments
#$trace=1;

sub
displaytype($)
{
local ($param) = @_;
local(%select,$sth,%type);

if( $$param{'Ttype'} eq "Intrinsic" ) {
	print $$param{'Tname'};
	return;
	}

if( $$param{'Ttype'} eq "Pointer" ) {
	$select = "SELECT * FROM Type WHERE Tid=".$$param{'Tbasetype'};
	$sth = $Dbh->query($select) || die $Dbh->errmsg();
	%type=$sth->fetchhash;
	displaytype(\%type);
	print " *";
	return;
	}

if( $$param{'Ttype'} eq "Struct" ) {
	print "struct ".$$param{'Tname'};
	return;
	}

if( $$param{'Ttype'} eq "Typedef" ) {
	print $$param{'Tname'};
	return;
	}

if( $$param{'Ttype'} eq "Union" ) {
	print "union ".$$param{'Tname'};
	return;
	}

if( $$param{'Ttype'} eq "Enum" ) {
	print $$param{'Tname'};
	return;
	}

print $$param{'Ttype'};
}

GetOptions("h=s" => \$headname);
 
if( !$headname ) { usage(); }  

$headname =~ s/^\.\///;

$Dbh = Mysql->connect($LSBDBHOST,$LSBDB,$LSBUSER, $LSBDBPASSWD) || die $Mysql::db_errstr;

$select = "SELECT * FROM Interface,Header,Type ";
$select.= "WHERE Istatus='Included' ";
$select.= "AND Iheader=Hid AND Hname=".$Dbh->quote($headname)." ";
$select.= "AND Ireturn=Tid";
print $select,"\n" if $trace;
$sth = $Dbh->query($select) || die $Dbh->errmsg();

for(1..$sth->numrows) {
	%entry=$sth->fetchhash;
	if( $entry{'Itype'} eq "Function" ) {
		if( $entry{'Ttype'} eq 'FuncPtr' ) {
			next;
			}
		displaytype(\%entry);
		printf " %s(",$entry{'Iname'};
		$select = "SELECT Tname,Ttype,Tbasetype FROM Type,Parameter ";
		$select.= "WHERE Pint=".$entry{'Iid'}." AND Ptype=Tid ";
		$select.= "ORDER BY  Ppos";
		print $select,"\n" if $trace;
		$sth2 = $Dbh->query($select) || die $Dbh->errmsg();
		if( $sth2->numrows != 0 ) {
			%entry2=$sth2->fetchhash;
			displaytype(\%entry2);
			for(2..$sth2->numrows) {
				%entry2=$sth2->fetchhash;
				print ", ";
				displaytype(\%entry2);
			}
		}
	printf ");\n";
	}
	if( $entry{'Itype'} eq "Data" ) {
		displaytype(\%entry);
		printf " %s;\n",$entry{'Iname'};
	}
	if( $entry{'Itype'} eq "Alias" ) {
		displaytype(\%entry);
		printf " %s;\n",$entry{'Iname'};
	}
	if( $entry{'Itype'} eq "Common" ) {
		displaytype(\%entry);
		printf " %s;\n",$entry{'Iname'};
	}
}
