#!/usr/bin/perl

my $file = $ARGV[0];
my $defaultFile = $ARGV[1];

#Read in the existing conf files
%confData = ReadConf($file);
%defaultData = ReadConf($defaultFile);

#Merge the keys from the default file into the conf file
MergeKeys(\%confData, \%defaultData);

#Write out the updates
WriteConf(\%confData, $file);

exit 0;

sub ReadConf($file)
{
   my $file = $_[0];
   local *FILE;
   my %confData;
   my $templateLineNum = 0;

   #open the file
   open(FILE, $file) || die;

   #Read each line in the file
   while ($line = <FILE>)
   {

      #See if this line has a key-value pair
      if ($line =~ /([^#\s].*)\=\"(.*?)\"/)
      {
      	my $key = $1;
	my $value = $2;
      
      	#Save the key-value pair in a hash
      	$confData{'keyValues'}{$key} = $value;
	
	#Save the template line number
	$confData{'templateLineNumbers'}{$key} = $templateLineNum;
	$confData{'fileTemplate'} .= "<--$templateLineNum-->\n";
	$templateLineNum ++;
	
	#See is the line is commented out, and record that fact	
	if ($line =~ /^\s*\#/)
	{
		$confData{'commentedFlags'}{$key} = 1;
	} else {
		$confData{'commentedFlags'}{$key} = 0;
	}
      } else {
      	#record the remaining lines in the file template
	$confData{'fileTemplate'} .= $line;
      }
      
   }

   close FILE;

   return %confData;
}

sub MergeKeys(%dstConfData, %srcConfData)
{
   local *dstConfData = $_[0];
   local *srcConfData = $_[1];

   my @theKeys = keys(%{$srcConfData{'keyValues'}});
   foreach $key (@theKeys)
   {
   	if (!defined($dstConfData{'templateLineNumbers'}{$key}))
	{
		$dstConfData{'keyValues'}{$key} = $srcConfData{'keyValues'}{$key};
		$dstConfData{'templateLineNumbers'}{$key} = $srcConfData{'templateLineNumbers'}{$key};
		$dstConfData{'commentedFlags'}{$key} = $srcConfData{'commentedFlags'}{$key};
	}
   }
}

sub WriteConf(%confData, $file)
{
   local *confData = $_[0];
   my $file = $_[1];
   local *FILE;
   my $newData = $confData{'fileTemplate'};
   
   #Go through each key and insert the key-value pair into the data
   my @theKeys = keys(%{$confData{'keyValues'}});
   foreach $key (@theKeys)
   {
   	my $markerToken = "<--$confData{'templateLineNumbers'}{$key}-->";
	my $expression;
	
	#Initialize the new expression string, respecting the commentedFlag
	if ($confData{'commentedFlags'}{$key})
	{
		$expression = "\#$key\=\"$confData{'keyValues'}{$key}\"";
   	} else {
		$expression = "$key\=\"$confData{'keyValues'}{$key}\"";
	}
	
   	#Put it at the appropriate marker, if it exists, otherwise, put it at the end of a file
	if ($newData =~ "$markerToken")
	{
		$newData =~ s/$markerToken/$expression\n$markerToken/;
	} else {
		$newData =~ s/\n*$/\n$expression\n/;
	}
   }
   
   #Make one last sweep to remove the remaining marker tokens
   $newData =~ s/\<\-\-[\d]*\-\-\>\n//g;
   
   #Write the data to the file
   open (FILE, ">$file");
   print FILE $newData;
   close FILE;
}