#!/usr/bin/perl -w

use strict;

my $addifnotfound=0;
my $errorifnotfound=0;
my ($sectionname,$replacementfile);

# really should use getopt...

if(defined $ARGV[0] && $ARGV[0] eq '-a') {
  $addifnotfound=1;
  ($sectionname,$replacementfile)=@ARGV[1..2];
} elsif(defined $ARGV[0] && $ARGV[0] eq '-e') {
  $errorifnotfound=1;
  ($sectionname,$replacementfile)=@ARGV[1..2];
} else {
  ($sectionname,$replacementfile)=@ARGV[0..1];
}

die "Usage: $0 [-a|-e] sectionname replacementfilename "
     ."< inputfile > outputfile" 
  unless defined $sectionname && defined $replacementfile;

my $insection=0;
my $found=0;

while(<STDIN>) {
  if($insection) {
    if(/^#---end$sectionname---/) {
      $insection=0;
    }
  } else {
    if(/^#---$sectionname---/) {
      $insection=1;
      $found=1;
      &printreplacement();
    } else {
      print $_;
    }
  }
}

die "end of section not found" if $insection;

die "section not found" if $errorifnotfound && !$found;

&printreplacement() if $addifnotfound && !$found;

sub printreplacement {
  open REPLACEMENT,"<$replacementfile"
    or die "couldn't open $replacementfile";
  while(<REPLACEMENT>) {
    print $_;
  }
  close REPLACEMENT;
}
