#!/usr/bin/perl
#
#	pesubst - replace strings in files
#	written by Jan Engelhardt, 2004-2007
#
#	This program is free software; you can redistribute it and/or
#	modify it under the terms of the WTF Public License version 2 or
#	(at your option) any later version.
#

use Getopt::Long;
use strict;

my($p_dest, $p_src, $p_mod, $o_fit);
&Getopt::Long::Configure(qw(bundling pass_through));
&GetOptions(
	"d=s" => \$p_dest,
	"f"   => \$o_fit,
	"m=s" => \$p_mod,
	"s=s" => \$p_src,
);

foreach my $file (@ARGV) {
	if (!open(IN, "< $file")) {
		warn "Could not open $file: $!\n";
		next;
	}

	my $data = join("", <IN>);
	close IN;

	if ($o_fit) {
		eval "\$data =~ s{$p_src}{".&fit_in($p_dest, length($p_src))."}g$p_mod";
	} else {
		eval "\$data =~ s{$p_src}{$p_dest}g$p_mod";
	}

	if (!open(OUT, "> $file")) {
		warn "Could not reopen $file: $!\n";
		next;
	}

	print OUT $data;
	close OUT;
}

sub fit_in ()
{
	my($str, $len) = @_;
	$str = substr($str, 0, $len);
	$str .= "\\x00" x ($len - length($str));
	return $str;
}
