#!/usr/bin/perl

# script to updateto mydestinations in /etc/postfix/main.cf
# to include the current ilst of virtual domains.

use Net::Domain qw(hostname hostfqdn hostdomain);

# get the list of domains

$tmpfile = "/tmp/$$";

system("ldapsearch -x > $tmpfile");

open(FD, $tmpfile) || die("Unable to read $tmpfile");
@lines = <FD>;
close(FD);
unlink($tmpfile);

$found = "";
$dn = "";
foreach $line (@lines) {
	chomp($line);
	# new object
	if ($line eq "") {
		if ($found ne "") {
			$domains[$domain++] = $newdomain;
		}
		$found = "";
		$newdomain = "";
		next;
	}
	if ($line =~ m/^objectClass: msgDomain/i) {
		$found = 1;
		next;
	}
	if ($line =~ m/^dn: /i) {
		$line = substr($line, 4, 9999);
		my @tmp = split(',', $line);
		$newdomain = substr($tmp[0], 3, 9999);
		next;
	}
}

$myfqdn = hostfqdn();

# We have to add it if the admin didnt already do it.
# now get main.cf
open(FD, "/etc/postfix/main.cf") || die("Unable to read /etc/postfix/main.cf");
@lines = <FD>;
close(FD);

@olines = ();
$oline = 0;
$changed = 0;

foreach $line (@lines) {
	if ($line =~ m/^mydestination\s*=\s*/) {
		foreach $newdomain (@domains) {
			# don't add it if already there or is our machine name
			if ($myfqdn =~ m/^$newdomain$/i) {
				next;
			}
			chomp($line);
			# does the domain already exist?
			if ($line =~ m/ $newdomain$/) {
				next;
			}
			if ($line =~ m/ $newdomain,/) {
				next;
			}
			# add it here
			$line = "$line, $newdomain\n";
			$changed = 1;
		}
	}
	$olines[$oline++] = $line;
}

if ($changed == 0) {
	exit(0);
}

open(FD, ">/etc/postfix/main.cf") || die("Unable to read /etc/postfix/main.cf");
foreach $line (@olines) {
	print(FD $line);
}
close(FD);
