#!/usr/bin/perl -w

# example:
#   /root/insertfile.pl /var/mailman/Mailman/mm_cfg.py afterline add_virtualhost -- add_virtualhost('uhurumovement.org','lists.uhurumovement.org')
#   /root/insertfile.pl /var/mailman/Mailman/mm_cfg.py afterline add_virtualhost -
# TODO:
#  could this just be replaced with patch?

die "Usage: $0 filename directive directivearg -- insertline1 insertline2\n" unless @ARGV >= 3;

my $TEST = 0;
if ($ARGV[0] eq '-test') {
    shift @ARGV;
    $TEST = 1;
}

# read input file
my $filename = shift @ARGV;
open(IN, "<$filename") || die "can't open $filename for read: $!";
my @inlines = <IN>;
close(IN);
my $n_input = scalar(@inlines);

# process directive to determine insertion point
my $directive = shift @ARGV;
my @outlines = ();
my $matchi = -1;
if ($directive eq 'afterline') {
    my $dirarg = shift @ARGV;
    die "no expression to match against" if !$dirarg || $dirarg eq '-' || $dirarg eq '--';
    my $i = 0;
    for(@inlines) {
	$matchi = $i if m/$dirarg/;
	$i++;
    }
    die "no match to '$dirarg' in $filename" unless $matchi > -1;
}
elsif ($directive eq 'append') {
    $matchi = $n_input - 1;
}
else {
    die "unknown directive '$directive'";
} 

die "insert position not found" if $matchi == -1;

# read insertion text
my $insertfile = shift @ARGV || die "no file to read insertions from";
my $insertion;
if ($insertfile eq '-') {
    my @insertion = <STDIN>;
    $insertion = join('', @insertion);
}
elsif ($insertfile eq '--') {
    $insertion = '';
    while(@ARGV) {
	my $line = shift @ARGV;
	$insertion .= "$line\n";
    }
}
else {
    open(INS, "<$insertfile") || die "can't read file $insertfile: $!";
    my @insertion = <INS>;
    close(INS);
    $insertion = join('', @insertion);
}
die "nothing to insert" unless $insertion;

# ouput lines preceding insertion point
for $i (0..$matchi) {
    push(@outlines,$inlines[$i]);
}

# output insertion
push(@outlines, $insertion);

# output the input lines after the insertion point
for $i (($matchi+1)..($n_input -1)) {
    push(@outlines,$inlines[$i]);
}

die "no output lines produced" unless @outlines;

# do the actual output
my $output = join("", @outlines);

if ($TEST) {
    print "Would output:\n'$output'\n";
}
else {
    # backup
    my $cmd = "cp '$filename' '$filename~'";
    system($cmd) and die "copy command failed: $cmd";

    # write
    open(OUT, ">$filename") || die "can't open $filename for write: $!";
    print OUT $output;
    close(OUT);
}

