#!/usr/bin/env perl

use strict;
use warnings;

my $fh = undef;
open($fh, '<', $ARGV[0]) or die "Could not read '$ARGV[0]', because: $!";
my @cont = <$fh>;

my %exports = ();
for(@cont) {
  m#^export\s+([^=\s]+)# and $exports{$1} = 1
}
my @exports = sort keys %exports;

my @lined = ();
for(0..$#cont) {
  $lined[$_] = [$_, $cont[$_]]
}
@lined = grep { $_->[1]!~m&^\s*#& } @lined;

for my $i(0..$#lined-1) {
  my $this = $lined[$i][1];
  my $next = $lined[$i+1][1];
  if($this=~m#^([^\s:]+):#) {
    my $targetPattern = $1;
    if($next=~m#^\t#) {
      my $cl = $lined[$i];
      push @$cl, qq#\t\@echo "== PATTERN $targetPattern TARGET \$@" >> makelogger\n#;
      push @$cl, qq#\t@  echo "  \\\$\$($_) = '\$($_)'" >> makelogger\n# for @exports;
      push @$cl, qq#\t@  echo "" >> makelogger\n#;
    }
  }
}

my %out = ();
for my $i(0..$#cont) {
  $out{$i} = $cont[$i]
}

for(@lined) {
  $out{$_->[0]} = $_
}

for my $i(0..$#cont) {
  my $tc = $out{$i};
  if(ref $tc) {
    print $tc->[$_] for 1..$#$tc
  } else {
    print $tc;
  }
}

