#
# verify_target_folder.pl
#
# tool to check for make-like dependency
#
# format: verify_target_folder.pl temp-folder other-command other-parameters
#
# the intention of this command is to modify conditionally a group of files,
# as would it have done by make. since there is no date information, the tool
# uses the contents of the files.
#
# the behaviour of this script is somehow specific:
# - it expects that the first parameter of other-parameters is a folder, where
#   files will be generated. other-command is a perl script and will be invoked
#   with "do".
# - it generates temp-folder
# - it invokes other-command, but replaces the first parameter with temp-folder
# - it then verifies temp-folder against the expected result folder (the first
#   parameter). therefor it compares all existing files in temp-folder with
#   equally named files in the other folder. differnt or not existing files
#   in the other folder are replaced by the temp-folder variants.
# - since the file is already so special, it brings its own comparison tool,
#   that way there is no need to install anything else, that tool compares
#   text files
#
# IMPORTANT:
#   since the used rename does not rename over file system boundaries (at least
#   it is not promised), choose your temp-folder accordingly
#

use strict;
#use warnings;

my $temp_folder = shift;
my $other_command = shift;
my $other_dest_folder = $ARGV[0];

# normalize $temp_folder
$temp_folder =~ s|\\|/|g;  # only slashes, please
$temp_folder =~ s|/$||;    # no slash at end of path

# modify command_line
$ARGV[0] = $temp_folder;

die "$temp_folder exists" if -e $temp_folder;

mkdir $temp_folder;

# to be sure, check the contents
die "unexpected files" if <$temp_folder/*>;

# perform the command, generate the files in the temp folder
my $result = do $other_command;

if ((! defined $result) && ($! || $@))
{
    die "system $other_command failed: $!\n$@";
}

#
# check now the files
#

my @temp_files = <$temp_folder/*>;

foreach my $temp_file (@temp_files)
{
    if ($temp_file =~ m|(.*)/(.*)|)
    {
        my $other_file = "$other_dest_folder/$2";
        
        if ((! -e $other_file) || compare_files($other_file, $temp_file) == 0)
        {
            unlink $other_file;
            rename $temp_file, $other_file;
        }
    }
}

unlink @temp_files;
rmdir $temp_folder;

sub get_contents_of_file
{
    my ($filename) = @_;

    open(FILE, "<$filename") or die "open failed: $filename";
    my @lines = <FILE>;
    my $text = join '', @lines;
    close FILE;

    $text
}

sub compare_files
{
    my ($file1, $file2) = @_;
    
    get_contents_of_file($file1) eq get_contents_of_file($file2)
}

