#! perl

use strict;
use warnings FATAL => 'all';
use autodie;

open my $fh, '<', 'config.perl';

my %invars = map { chomp; split /=/, $_, 2 } <$fh>;
my %outvars;

close($fh);

for(;;) {
	my $changed;
	while(my ($key, $val) = each %invars) {
		next unless $val =~ /^(?:[^\\\$\`]|\$(?:\{\w+}|\w+)|\\.)+$/;
		$val =~ s{\\(.)|\$(?:\{(\w+)\}|(\w+))}{$1 // $outvars{$2 // $3} // ''}eg;
		next if exists $outvars{$key} && $val eq $outvars{$key};
		$outvars{$key} = $val;
		$changed = 1;
	}
	last unless $changed;
}

print "#! $outvars{PERL}\n\nBEGIN {\n";

while(my ($key, $val) = each %outvars) {
	$val =~ s/[\\"\$\@]/\\$&/g;
	print "\tour \$$key = \"$val\";\n";
}

print "}\n\n";

my $pod;
while(<ARGV>) {
	$pod = 1 if /^=(\w+)(?:\s|$)/;
	print unless $pod;
	$pod = 0 if /^=cut(?:\s|$)/
}
