#!/usr/bin/perl
# ( ^^^^ when run with -n it tries to read in files named after the args. e.g. foo=bar)
#
# Takes command-line args in the format:
#   foo=bar [[include:]bar=foobar] ...
# and parses stdin, replacing @foo@ with bar and @bar@ with foobar.
# All output goes to stdout.
#
# Intended to be used as a simple parser for Makefile.in-type files.
#
# Special key type:
#   include:KEY=VAL
# will try to read the file VAL and import it in place of @KEY@.
#
# Optional arguments:
# [-f filename] will read in that file. It must be in the form KEY=VALUE, with one key/value per line.
# [-c] will enable "cleanup mode". Any @TOKENS@ in the input stream which were not explicitely
#      assigned values will be parsed out of the output. Without this option, the raw @TOKEN@
#      would go into the output.
#
# License: public domain
# author: stephan <sgbeal@users.sourcceforge.net>
# CVS Revision: $Revision: 1.7 $

BEGIN {
  $STRIP_LEADING_DASHES = 1; # if set to one, --foo=bar is same as foo=bar
  $op_cleanup = 0; # strip un-parsed @TOKENS@ from the input.
  if( ! @ARGV ) {
    print "Usage: $0 foo=bar [bar=foobar] [argN=valN]...\n";
    exit 1;
  }

  @args = ();
  for( $i = 0; $i < @ARGV; $i++ )
  {
          $a = $ARGV[$i];
          if( $a eq "-f" ) {
                  $fn = $ARGV[++$i];
                  open( INFILE, $fn ) || die "Could not open input file [$fn].";
                  @foo = <INFILE>;
                  foreach $f (@foo) {
                          chomp($f); push( @args, $f );
                  }
                  close INFILE;
                  next;
          }
          if( $a eq "-c" ) {
                  $op_cleanup = 1;
                  next;
          }
          push( @args, $a );
  }
  #print join( "\n", @args )."\n";
  
  %args = ();

  foreach $a ( @args ) {
    next unless $a =~ m|([^=]+)\s*=\s*(.*)|;
    $key = $1;
    $val = $2;
    if( $STRIP_LEADING_DASHES ) { $key =~ s/^-+//; }
    #print STDERR ": [$key]=[$val]\n";
    if( $key =~ m|^include:(.+)| ) {
      $key = $1;
      open INFILE, "<$val" or die "Cannot open file '$val', as requested by \@include:$key@!";
      @foo = <INFILE>;
      close INFILE;
      $val = join( "", @foo );
    }
    $args{$key} = $val;
  }
} # /BEGIN

while( <STDIN> ) {

  $loop = true;
  while( $loop ) {
          $cp = $_;
          foreach $k (keys(%args)) {
                  $v = $args{$k};
                  next unless $_ =~ s|\@$k\@|$v|g;
#                  print STDERR "replacing $k --> $v\n";
          }
          $loop = 0 if $cp eq $_;
  }
  if( $op_cleanup ) {
          while( $_ =~ s|\@\S+\@||g ) {}
  }
  print;
}

exit 0;
