#!perl -w
use strict;

# import some modules
use File::Spec;
use File::Copy;
use File::Glob ':glob';
use File::Compare;
use File::stat;

if (@ARGV != 3) {
  print "usage:   make_cfg <ssa_script> <outputDir> <hw_config>\n";
  print "example: make_cfg ../ssa/system/update_exported_makefiles.pl ../__out__/ssa_config GPRS_DSAMPLE_AMR_NW4\n";
  exit;
}

my $script;
my $scriptDir;
my $outDir;
my $config=$ARGV[2];

# find the perl script
(-e $ARGV[0]) || die "Script $ARGV[0] could not be found!";
($_,$scriptDir,$script) = File::Spec->splitpath($ARGV[0]);
#print "$scriptDir\n";

# calculate outputdir relative to script dir, so we don't need to CD back
$outDir = calcRelativePathFromLocation($ARGV[1], $scriptDir);
#print "$outDir\n";

# cd into the script directory and call it
chdir($scriptDir) || die "Can't cd to $scriptDir: $!\n";

# delete gen_cfg_values.mak to force re-generation
(-e "gen_cfg_values.mak") && unlink("gen_cfg_values.mak");

# call the script
system ("perl $script $config") && die "Can't call $script: $!\n";

# copy all cfg files
my @cfgFiles = bsd_glob("config/*.cfg");

foreach (@cfgFiles) {
  my ($drive,$directories,$file) = File::Spec->splitpath($_);
  if(compare("$directories$file","$outDir/$file") != 0)
  {
    print "Copying $_ to $outDir !\n";
    copy($_,$outDir ) || die "Could not copy $_ to $outDir: $!\n";
  }
}

# move rv_swe.h to assure that this one is used
my $rvFile = "../Riviera/rv/rv_swe.h";
my $newRvFile = "$outDir/rv_swe.h";

if(compare($rvFile,$newRvFile) != 0)
{
  print "Copying $rvFile to $outDir !\n";
  copy($rvFile, $outDir ) || die "Could not copy $rvFile to $outDir: $!\n";
}

# if rv_swe.h in SSA has been created - remove it
if(-w $rvFile) {
  print "Deleting $rvFile !\n";
  unlink($rvFile) || die "Could not delete $rvFile: $!\n";
}

# if the file is older than the script (thanks to ABC) touch it;
if (stat($newRvFile)->mtime < stat($script)->mtime) {
  my $now = time;
  utime ($now, $now, $newRvFile) ;
}


########################################################
# correct obscure behavior of File::Spec->abs2rel,
# which inserts a drive letter befor a relative path !!!
#
sub calcRelativePathFromLocation
{
  my ($drive,$directories,$file);

  ($drive,$directories,$file) = File::Spec->splitpath( File::Spec->abs2rel ($_[0], $_[1]) );

  return File::Spec->catpath("",$directories,$file);
}
########################################################
