#! /usr/local/apps/perl/current/bin/perl
#  /usr/local/bin/perl56 -I/usr/local/lib/metaps/perl
#
# Script to update GRIB2 tables from database
# Usage: $0 [version]
#

use strict;
use File::Path;
use File::Basename;
use File::Copy;
use DBI;

my $basedir=dirname($0);  # the "definitions" dir in grib_api workspace

my $db="fm92_grib2";
my $host="grib-param-db-prod.ecmwf.int";
my $user="ecmwf";
my $pass="";
my $filename; my $filebase; my $out; my $conceptDir;
my $query; my $q; my $qh;
my $tablesVersion=6;          # default GRIB2 version
my %records;

# Check if user has provided arg to set table version
if ( @ARGV) {
	$tablesVersion = $ARGV[0];
	if ($tablesVersion !~ /^\d+$/ ) {
		die "Bad version number: '$tablesVersion'.  Please enter a positive integer.\n";
	}
}
print "GRIB2 tablesVersion set to $tablesVersion\n";

my $dbh  = DBI->connect("dbi:mysql(RaiseError=>1):database=$db;host=$host",$user,$pass) or die $DBI::errstr;

###########################################################################################
sub create_parameter_tables {
	my $tablesDir="$basedir/grib2/tables/$tablesVersion";
	my $tableFile="";

	my $query="select discipline_id,category_id,param_id,name,units ".
				"from parameter_specs order by discipline_id,category_id,param_id";

	my $qh=$dbh->prepare($query);
	$qh->execute();

	while (my ($discipline,$category,$code,$name,$units)=$qh->fetchrow_array )
	{
		my $f="$tablesDir/4.2.$discipline.$category.table";
		if ($f ne $tableFile) {
			print "discipline=$discipline category=$category;\n";
			$tableFile=$f;
			if ($out) {
				# Write out what we stored in 'records' into the PREVIOUS file
				print $out "# Automatically generated by $0 from database $db\@$host, do not edit\n";
				my @keys = sort { $a <=> $b } (keys %records);
				foreach my $key (@keys) { print $out $records{$key}."\n"; }
				close $out;
				%records=();
				@keys=();
			}
			system("p4 edit $tableFile");
         open($out,"> $tableFile") or die "unable to open $tableFile";
      }
      next if ($code !~ /^\s*[0-9]/);
		if (!$units) { $units="-"; }
		my $codeText = "$code $code";
		my $unitsText = "($units)";
		if ($code =~ /\d\-\d/ ) {
			# This is a range like 24-191 e.g. for Reserved entries
			$codeText = "#$code";  # Comment out
			$unitsText = "";       # Units do not make sense
		}
		$records{$code}="$codeText $name $unitsText";
	}
	# Now write the final records set into the last opened file
	if ($out) {
		print $out "# Automatically generated by $0 from database $db\@$host, do not edit\n";
		my @keys = sort { $a <=> $b } (keys %records);
		foreach my $key (@keys) { print $out $records{$key}."\n"; }
	}
	close $out;
}

###########################################################################################
sub create_tables {
	my $tablesDir="$basedir/grib2/tables/$tablesVersion";
	my $tableFile="";

	my $query="select section_id,ctable_id,code,meaning from ctable_specs order by section_id,ctable_id";

	my $qh=$dbh->prepare($query);
	$qh->execute();

	while (my ($section,$table,$code,$meaning)=$qh->fetchrow_array )
	{
		my $f="$tablesDir/$section.$table.table";
		if ($f ne $tableFile) {
			print "section=$section table=$table\n";
			$tableFile=$f;
			if ($out) {
				print $out "# Automatically generated by $0 from database $db\@$host, do not edit\n";
				my @keys = sort { $a <=> $b } (keys %records);
				foreach my $key (@keys) { print $out $records{$key}."\n"; }
				close $out;
				%records=();
				@keys=();
			}
			system("p4 edit $tableFile");
         open($out,"> $tableFile") or die "unable to open $tableFile";
        }
		next if ($code =~ /-/) ; 
		$records{$code}="$code $code $meaning";
	}
	close $out;
}
 
create_parameter_tables();
 
#create_tables();

