#!/usr/bin/perl
# ISDK - Information System Development Kit
# Copyright (C) 1998-1999 Szilard Hajba, Peter Vazsonyi
#
# 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

sub parse_esql {
    my ($file)=@_;
    my $ln,$tbl,$tab,$key,$two,$list;
    open FILE, $file;
    while ($ln=<FILE>) {
    	$tab="" if (! $tbl);
	if ($ln =~ /^\s*CREATE\s*TABLE\s*(\w+)\s*\(/) {
	    $tbl=$1; $tab=$1;
	} elsif ($ln =~ /^\s*(\w+)\s+([\@a-zA-Z_0-9()]+)(\s*,?\s*(--.*)?)?$/) {
	    $key=$1;
	    $two=$2;
	    $two =~ s/\@percent/float8/g;
	    $two =~ s/\@money/float8/g;
	    $two =~ s/\@quantity/float8/g;
	    $two =~ s/\@persid/char(5)/g;
	    $two =~ s/\@fix85/float8/g;
	    $two =~ s/\@fix83/float8/g;
	    $two =~ s/\@fix82/float8/g;
	    $two =~ s/\@fix43/float8/g;
	    if ($ln =~ '--\*' ) {
		$two .= " NOT NULL";
		$idx[$#idx+1]=$key;
	    }
	    if ($ln =~ '--!' ) {
		$two .= " NOT NULL";
	    }
	    $fields{$key}=$two if ($tbl);
	    $list[$#list+1]=$key;
	} elsif ($ln =~ /\);/) {
	    $tbl="";
	} elsif ($ln !~ /^\s*(--.*)?$/ && $tbl ) {
	    print STDERR "Bad field?: $ln";
	}
	if ($tab && (! $tbl)) {
	    print "CREATE TABLE $tab (\n";
	    print "    last_modify timestamp NOT NULL DEFAULT now(),\n";
	    print "    deleted int4 NOT NULL DEFAULT 0,\n";
	    @l=();
	    foreach $key (@list) {
		$l[$#l+1]= "$key " . $fields{$key};
	    }
	    print "    ",join(",\n    ", @l);
	    print "\n);\n";
	    if (@idx) {
		$name="_$tab" . "_" . 
		    join ('_', @idx);
		$name = "_$tab"."_uniq" if (length($name) > 32);
		print "CREATE UNIQUE INDEX $name ON $tab(",
		    join(", ", @idx),");\n";
	    }
	    @idx=();
	    @list=();
	    %fields={};
	}
	if ( ! ($tab || $tbl) ) {
	    $ln =~ s/\@percent/float8/g;
	    $ln =~ s/\@money/float8/g;
	    $ln =~ s/\@quantity/float8/g;
	    $ln =~ s/\@persid/char(5)/g;
	    $ln =~ s/\@fix85/float8/g;
	    $ln =~ s/\@fix83/float8/g;
	    $ln =~ s/\@fix82/float8/g;
	    $ln =~ s/\@fix43/float8/g;
	    print $ln;
	}
	
    }
    close FILE;
}

$ARGV[0] || exit 1;
print <<EoT;
----------------    WARNING !!!    ----------------
--------------    Generated file    ---------------
----------------    Do not edit    ----------------
EoT
parse_esql($ARGV[0], be, lst, idx);
foreach $tab (keys %be) {
}

