#!/usr/bin/env perl
use strict;
use warnings;

# should do nothing if line is already present where it should be.
# should have error if needle line not found
# should have error if needle line found more than once

# bug: this is not a perfect solution, it's not a parser for conf files (as it is frequently used)
# it'll warn you if the replacement was already made, but not if the line is somewhere unexpected,
# or if the wrong value was set in an ini file
# just a hack.

my $needle = shift || die "$0: no line to search for (should be a perl regex)";
my $new = shift || die "$0: no line to replace with (should be a string)";
my $file = shift || die "$0: no filename to replace on";

my $wholething = slurpfile($file);
my $matches;
my $alreadythere = $wholething =~ /(\n$needle\s*\n$new)/;
if ($alreadythere) {
  die "$0: $new already present";
} else {
  $matches = $wholething =~ s/(\n$needle\s*\n)/$1$new\n/gs;
  if ($matches == 1) {
    printfile($file, $wholething);
    } else {
    die "$0: should have 1 match, but have: $matches\n"
  }
}


sub printfile {
  my $file = shift || die "no file";
  my $printme = shift || die "nothing to print";
  open(FILE, ">$file") or die $!;
  print FILE "$printme\n";
}






sub slurpfile {
  my $file = shift || die "$0: no file";
  open(FILE, $file) or die $!;
  my $wholething;
  while (<FILE>) {
    $wholething .= $_;
  }
  return $wholething;
}
