#!/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.

# Variables:
#	$fml_obj{form}{name}=tag
#	$fml_tbl{form}=table
#	$sql_obj{table}{name}=type

sub parse_fml {
    my ($file)=@_;
    undef $/;
    open FILE, $file;
    my($fml, $line, $form)=(<FILE>, "");
    $fml =~ s/#@(\w+)[^\n]*\n/\(string name=$1\)/g;
    $fml =~ s/#[^\n]*\n//g;
    $fml =~ s/\n[ \t]*/ /g;
    while ($fml) {
	if ($fml =~ /^[^(]*\(\/?(\w+)[^)]*name=(\w+)[^)]*\)/) {
	    my ($tag, $name)=($1, $2);
	    if ($tag eq 'form') {
		$form=$name;
		if ($fml =~ /^[^(]*\(\/?\w+[^)]*table=(\w+)[^)]*\)/) {
		    $fml_tbl{$form}=$1 if ($fml =~ /^[^(]*\(\/?\w+[^)]*table=(\w+)[^)]*\)/);
		}
	    } elsif (grep(/ $tag /, ' form tlist alarm pixmap ')) {
#		$line.="$tag $name\n";
	    } else {
		$fml_obj{$form}{$name}=$tag;
	    }
	}
	$fml =~ s/^[^(]*\([^)]*\)[^(]*//;
    }
    close FILE;
}

sub parse_sql {
    my ($file)=@_;
    my $ln;
    open FILE, $file;
    while ($ln=<FILE>) {
	if ($ln =~ /^\s*CREATE\s*TABLE\s*(\w+)\s*\(/) {
	    $tbl=$1;
	} elsif ($ln =~ /^\s*CREATE\s*/) {
	    $tbl="";
	} elsif ($ln =~ /^\s+(\w+)\s*(\@?\w+).*$/) {
	    $sql_obj{$tbl}{$1}=$2 if ($tbl);
	}
    }
    close FILE;
}

while ($ARGV[0]) {
    parse_fml($ARGV[0]) if $ARGV[0] =~ /\.fml$/;
    parse_sql($ARGV[0]) if $ARGV[0] =~ /\.esql$/;
    shift;
}

$fil="";
foreach $form (keys %fml_tbl) {
    if ($fml_tbl{$form}) {
	$fl="";
	$ln="";
	foreach $name (keys %{$fml_obj{$form}}) {
	    $name =~ s/^__//;
	    if ($name !~ /^_/) {
		if (! $sql_obj{$fml_tbl{$form}}{$name}) {
		    $ln.=" $name";
		}
	    }
	}
	$fl.="    Extra FML fields:$ln\n" if $ln;
	$ln="";
	foreach $name (keys %{$sql_obj{$fml_tbl{$form}}}) {
	    if ((!$fml_obj{$form}{$name}) && (!$fml_obj{$form}{"__$name"})
		    && ($name ne "last_modify") && ($name ne "deleted")) {
		$ln.=" $name";
	    }
	}
	$fl.="    Extra SQL fields:$ln\n" if $ln;
	$fil.="Form '$form', table '".$fml_tbl{$form}."':\n$fl" if $fl;
    } else {
	$fil.="Form '$k' doesn't have direct database connection.\n";
    }
}
print $fil;
