#!/usr/bin/perl

use strict;
use File::Find;
use File::Temp qw(tempfile);
use File::Copy qw(copy);

my @files;
my $domainName;
my @targetDirs;

sub fileFilter
{
	-d $_ && return;
	/^\./ && return;

	push @files, $File::Find::name;
}


if (scalar @ARGV != 1) {
	printf("Usage: %s  domain_name.\n", $0);
	print("List of directories to be processed are passed through STDIN.\n");
	exit(1);
}

$domainName = $ARGV[0];
@targetDirs = <STDIN>;
if (scalar @targetDirs == 0) {
	print("Error: empty directory list\n");
	exit 1;
}
chomp(@targetDirs);


find(\&fileFilter, @targetDirs);

foreach my $originalConf (@files) {
	my $errPrefix = "Skip modifying ${originalConf}. Error on ";

	open my $fin, "<", $originalConf or next;
	my $configContent = join('', <$fin>) or do {
		print "$errPrefix reading: $!\n";
		close(fin);
		next;
	};

	my $substCount = ($configContent =~ s/\@domain_name\@/$domainName/g);
	close $fin;
	next unless $substCount >= 1;

	my ($fout, $modifiedConf) = eval {tempfile("skel_fileXXXXX", UNLINK => 1, DIR => '/tmp')};
	do {
		print "$errPrefix temp file creation: $@\n";
		next;
	} if $fout == undef;

	if (print $fout $configContent) {
		$fout->flush;
		print "$errPrefix replacing old config with fixed one: $!" unless copy $modifiedConf, $originalConf;
	} else {
		print "$errPrefix save modified data in temprary file: $!\n";
	}
	close $fout;
}
