use strict;

# --------------------------
# readFile(fileName)
#
#  returns the complete file contents
#
sub readFile
    {
    my $fileName = shift;
    my $bunch;
    my $result;
    my $did;

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

    return $result;
    }

# -----------------------
# writeFile(fileName,contents)
#
#  creates new file and writes entire
#  file contents. Return "ok" if so,
#  or "" if not.
#
sub writeFile
{
    my $fileName = shift;
    my $contents = shift;
    my $did;

    #
    # Delete existing file, if any.
    #
    unlink ($fileName) if(-e $fileName);

    $did = open(FILE,">$fileName");
    if($did)
    {
        binmode FILE;           # Bite me, Windows! --dvb
        print FILE $contents;
        close FILE;
        return "ok";
    }

    print STDERR ("Trouble writing $fileName\n"); 
    return ""; 
} 
    
    
# Globals
my $me;
sub markdown($)
{
    my $filename = shift;
    my $mdHtml = `perl $me/Markdown_1.0.1/Markdown.pl $filename`;
    return $mdHtml;
} 

sub zlog
{
    my $s = join(" ",@_);
    print STDERR "$s\n";
}

sub help
{
    print << "EOP";

This tool executes a sequence of commands for templatey things.
    
Like:
    readFile:<filename>=
      Read in a file.
    
    writeFile:<filename>=
      Read in a file.
    
    md:<filename>=<key>
      Replace --key-- with HTML from the Markdown file.
    
    file:<filename>=<key>
      Replace --key-- with contents of file.
    
    lit:<value>=<key>
      Replace --key-- with literal value
    
    bump:<value>=
      Look for the literal string <value> followed by a decimal integer, and increment the integer.
    
    find:<filename>:<pattern>=<key>
      Open up filename and look for a line with pattern. Replace --key-- with the rest of that line.
      example, find:version.txt:"version = "=version, to replace --version-- with the extracted value.
EOP
}

sub main(@) 
{
    if(scalar(@_) == 0)
    {
        help();
        return;
    }

    my $fileContents = "";
    my @argv = @_;
    for my $arg (@argv) 
    { 
        if($arg =~ /^(.*?):(.*?)=(.*?)$/) 
        {
            my $action = $1;
            my $value = $2;
            my $key = $3;
            
            my $replacer = "";
            
            if($action eq "md")
            {
                $replacer = markdown($value);
                zlog("--$key-- <--mdfile:",$value,"(",length($replacer),"bytes)");
            }
            elsif($action eq "file")
            {
                $replacer = readFile($value);
                zlog("--$key-- <--file:",$value,"(",length($replacer),"bytes)");
            }
            elsif($action eq "lit")
            {
                $replacer = $value;
                zlog("--$key-- <--",$value);
            }
            elsif($action eq "readFile")
            {
                $fileContents = readFile($value);
                zlog("read",$value,"(",length($fileContents)," chars)");
            }
            elsif($action eq "writeFile")
            {
                writeFile($value,$fileContents);
                zlog("write",$value,"(",length($fileContents)," chars)");
            }
            elsif($action eq "bump")
            {
                if($fileContents =~ /^(.*$value)([0-9]+)(.*)$/s)
                {
                    my $front = $1;
                    my $number = $2;
                    my $back = $3;
                    
                    $number++;
                    
                    $fileContents = "$front$number$back";
                    zlog("bumped $value to $number");
                }
                else
                {
                    zlog("bump: no $value in $fileContents");
                }
            }
            elsif($action eq "find")
            {
                if($value =~ /^(.*?):(.*?)$/)
                {
                    my $fileName = $1;
                    my $pattern = $2;
                    my $k = readFile($fileName);
                    if($k =~ /^.*$pattern(.*)$/m)  # any individual line...
                    {
                        $replacer = $1;
                    }
                }
            }
            else
            {
                zlog("unknown action: $action");
            }

            if($replacer)
            {
                $fileContents =~ s/--$key--/$replacer/g;
            }
        }
        else
        {
            zlog("bad structure: $arg");
        }
    }
}

$me = $0; # full path to this script
if($me =~ /^(.*)\/.*$/)
{
    $me = $1;
}
else
{
    $me = ".";
}
zlog("me is $me");
main(@ARGV);


