#!/usr/bin/perl
# oneliner would be nice
use Digest::MD5 qw(md5 md5_hex);
$debug=1;
#/usr/bin/perl -e 'local $/; local $_ = <>; ($_=~m/### BEGIN kraken ... ###.*### END kraken ###/s)?exit 0:exit 1' hosts
# 2 files
# original file
# snipplet to merge in
#
# snipplet is in file?
# no
# append
# yes
# current?
# yes
# exit
# no
# exchange
$file=shift;
$snip=shift;
open FILE, "<$file" or die "$!\n";
open SNIP, "<$snip" or die "$!\n";
# read the whole files in slurp mode :)
{ local $/; $f=; $s=}
close FILE;
close SNIP;
$s=~s/^\s*//sg;
$s=~s/\s*$//sg;
$md5_snip=md5_hex($s);
print "Snip hash: ".$md5_snip."\n" if ($debug);
# find pattern
($patt1,$patt2)=($s=~m/(^### BEGINPUPPET .*###).*(### ENDPUPPET .* ###$)/s);
if ((not defined $patt1) or (not defined $patt2)) {
print "$s\nIs not a valid puppet snip\n" if ($debug);
exit 1;
}
print "Patt1: $patt1\nPatt2: $patt2\n" if ($debug);
($infile)=($f=~m/($patt1.*$patt2)/s);
if (defined $infile) {
print "Infile string:\n$infile\n" if ($debug);
print "Infile hash: ".md5_hex($infile)."\n" if ($debug);
if ($md5_snip eq md5_hex($infile)) {
# nothing to do
print "nothing to do\n" if ($debug);
exit;
} else {
# replace
print "replace\n$infile"."with\n$s" if ($debug);
$f=~s/$patt1.*$patt2/$s/sg;
system("cp -f $file $file.puppet");
open TMP,">$file.tmp";
print TMP $f;
close TMP;
system("mv -f $file.tmp $file");
}
} else {
# append
system("cp -f $file $file.puppet");
open TMP,">$file.tmp";
print TMP $f;
print TMP "\n$s";
close TMP;
system("mv -f $file.tmp $file");
}