#!perl -w
use strict;

use File::Glob ':glob';
use File::Spec;

# find the config file
@ARGV > 2 || die "Usage:\tgen_configDef.pl <configDef_Template> <configDef_OutFile> [flags]*\n";


# define global variables
my $infFile       =$ARGV[0]; 
my $tmplFile      =$ARGV[1];
my $configDefFile =$ARGV[2];


shift(@ARGV);
shift(@ARGV);



my %infProperties;
# parse the remaining command line
foreach (@ARGV) {
  /^(\w+)=(\d+)/;
  if (defined($1)) {
    if (defined($2)) {
      $infProperties{$1} = $2;
    }
  }
}


# parse the template file
#
open (IN,"<$tmplFile")||die "Can't open $tmplFile !\n";

my %tmplProperties;
my $line;
while(defined($line = <IN>))
{
  # ignore comments (starting with #)
  if($line =~ /^\s*\#/) {
    next;
  }

  # ignore empty lines
  if($line =~ /^\s+$/) {
    next;
  }

  # remove trailing \n
  chomp($line);

  if ($line =~ /^(\w+)/) {
    my $orgName = $1;
    if ($' =~ /^=(\d+|\w+)/) {
      $tmplProperties{$orgName} = $1;
    }
    else {
      $tmplProperties{$orgName} = "";
    }
  }
  else {
    next;
  }
}
close IN;

# do the mapping/filtering
my %finalProperties;
foreach (keys(%infProperties)) {
  if (exists $tmplProperties{$_}) {
    if ($tmplProperties{$_} =~ /^\d+/) {
      # a value
      $finalProperties{$_} = $infProperties{$_};
#      print "$_=$infProperties{$_}\t\toverridden\n";
    }
    elsif ($tmplProperties{$_} =~ /^\w+/) {
      # a mapping
      $finalProperties{$tmplProperties{$_}} = $infProperties{$_};
#      print "$tmplProperties{$_}=$infProperties{$_}\t\tmapped from $_\n";
    }
    else {
      # used
      $finalProperties{$_} = $infProperties{$_};
#      print "$_=$infProperties{$_}\t\tused\n";
    }
    # delete the template entry, so later we can process the remaining defaults
    delete ($tmplProperties{$_});
  }
  else
  {
#    print "$_=$infProperties{$_}\t\tignored\n"
  }

}

# write the configDef file
#
open (OUT,">$configDefFile")||die "Can't open $configDefFile !\n";
$configDefFile =~ /(\w+)(.\w+$)/;
my $name = $1;

print OUT "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print OUT "<configDef description=\"auto generated from: $infFile\" name=\"$name\" reference=\"none\">\n";

# first the ones that have been overridden/mapped from the commandline
foreach (keys(%finalProperties)) {
  print OUT "<property name=\"$_\" value=\"$finalProperties{$_}\"/>\n";
}

# now the defaults
foreach (keys(%tmplProperties)) {
  if ($tmplProperties{$_} =~ /^\d+/) {
    print OUT "<property name=\"$_\" value=\"$tmplProperties{$_}\"/>\n";
  }
}

print OUT "</configDef>\n";

close OUT;
