#!/usr/bin/perl

use Cwd;
use strict;

# +----------------------------
# | usage:
# |   templater infile outfile key replace key replace key replace...
# |


# +-------------------------
# | mp_read_file(filename[,error_ref])
# |
# | returns the complete file contents
# |
# |
# |     in: filename -- name (path) of file to read
# |
# | return: one long string with the whole file, or
# |         empty string if no such file or empty file.
# |
# |         (use Perl's -e if you really really care whether
# |         the file was there...)
# |

sub mp_read_file
  {
  my ($filename,$error_out) = (@_);
  my $bunch;
  my $file_contents;
  my $did;

  # (return error if ref provided)

  if($error_out)
    {
    $$error_out = (-f $filename) ? 0 : -1;
    }

  # (read the whole file, if present. else "")

  if(open(FILE,$filename))
    {
    binmode FILE;    # Bite me, Windows! --dvb
    while(read(FILE,$bunch,32000))
      {
      $file_contents .= $bunch;
      }
    close FILE;
    }

  return $file_contents;
  }

# -----------------------
# mp_write_file(filename,contents)
#
# creates new file and writes entire
# file contents. Return "ok" if so,
# or "" if not.
#
# |
# |     in: filename -- name of file to create (or replace)
# |         contents -- string of all the bytes to put into file
# |
# | return: 0 for success, <0 for error
# |

sub mp_write_file($$)
  {
  my ($filename,$contents) = (@_);

  my $did;

  #
  # If filename is "", print it to stdout
  # and that is all.
  #

  if($filename eq "")
    {
    print $contents;
    return "";
    }

  #
  # Delete existing file, if any.
  #

  unlink ($filename) if(-e $filename);

  $did = open(FILE,">$filename");
  if($did)
    {
    binmode FILE;    # Bite me, Windows! --dvb
    $did = print FILE $contents;
    close FILE;
    return $did ? 0 : -1;
    }

  return -1;
  }

sub fixupFile($$%)
{
    my ($inFile,$outFile,$fixersRef) = (@_);

    print ":: inFile: $inFile\n";
    print ":: outFile: $outFile\n";

    my $s = mp_read_file($inFile);

    foreach my $key (sort(keys(%$fixersRef)))
    {
        my $value = $$fixersRef{$key};
        print ":: $key ==> $value\n";
        $s =~ s/--$key--/$value/gs;
    }

    mp_write_file($outFile,$s);
}

sub main
{
    my $inFile = shift;
    my $outFile = shift;
    my %replacements;
    while(scalar(@_) > 1)
    {
        my $key = shift;
        my $value = shift;
        $replacements{$key} = $value;
        fixupFile($inFile,$outFile,\%replacements);
    }
}

main(@ARGV);

# end of file
