#!/usr/bin/perl

# inplace upgrade script for LDAP 
# has to create its own ldap root password
# runs as root, expects to be called only from in place upgrade.
# as it assumes that LDAP is startable.
# this script is recallable, it carefully does not change anything
# if run again.

BEGIN {
	use File::Basename();
	$newdir = File::Basename::dirname($0);
	unshift (@INC, "$newdir");
}

use	msglib;

$slapconf = "$msgldapdir/slapd.conf";
$slapinit = "$msginitdir/ldap";
$imapconf = "/etc/imapd.conf";

$rootdn = "";
$rootpw = "";
$saverootpw;

# put our password into slapd.conf, save the old pwd,
# get the bind addr, start ldap
sub
slapd_in
{
	my ($ndx, $line, @arr);

	open(FD, "$slapconf") || die "Unable to read $slapconf";
	@slapfile = <FD>;
	close(FD);

	for ($ndx = 0; $ndx < scalar(@slapfile); $ndx++) {
		$line = $slapfile[$ndx];
		if ($line =~ /^rootdn[ \t]/) {
			@arr = split("[ \t]+", $line, 2);
			$rootdn = $arr[1];
			chomp($rootdn);
			$rootdn =~ s/"//g;
		}
		if ($line =~ /^rootpw[ \t]/) {
			@arr = split("[ \t]+", $line, 2);
			$saverootpw = $line;
			$slapfile[$ndx] = "rootpw\t\t$rootpw\n";
		}
	}

	open(FD, ">$slapconf") || die "Unable to write $slapconf";
	foreach $line (@slapfile) {
		print FD $line;
	}
	close(FD);

	system("$slapinit stop > /dev/null 2>&1");
	sleep(2);
	system("killall -15 slapd >/dev/null 2>&1");
	sleep(2);
	system("killall -9 slapd >/dev/null 2>&1");
	sleep(2);
	unlink("/var/run/slapd.pid") if ( -e "/var/run/slapd.pid" );
	unlink("/var/run/slapd/slapd.pid") if ( -e "/var/run/slapd/slapd.pid" );
	system("$slapinit start > /dev/null 2>&1");
	sleep(2);
}

# reverse of slapd_in, stop slapd, remove ourself from slapd.conf.
sub
slapd_out
{
	my ($ndx, $line, @arr);

	open(FD, "$slapconf") || die "Unable to read $slapconf";
	@slapfile = <FD>;
	close(FD);

	for ($ndx = 0; $ndx < scalar(@slapfile); $ndx++) {
		$line = $slapfile[$ndx];
		if ($line =~ /^rootpw[ \t]/) {
			$slapfile[$ndx] = $saverootpw;
			last;
		}
	}

	open(FD, ">$slapconf") || die "Unable to write $slapconf";
	foreach $line (@slapfile) {
		print FD $line;
	}
	close(FD);

	system("$slapinit stop > /dev/null 2>&1");
	sleep(2);
	system("$slapinit start > /dev/null 2>&1");
	sleep(2);
}

# update the system aliases for the given dn.
# at this point all domains are of type msgDomain
sub
do_aliases
{
	my ($domaindn) = @_;
	my ($vdomain, $aliasentry, $aliasdn, $aliascn, $item, $i);
	my (@ownerlist, $postmaster, $mailerdaemon);
	my (@memberlist, %attrpairs, $hashref);
	my ($mesg, $aliasattrs);

	$vdomain = getfirstfromdn($domaindn);

	# get the system aliases, create them if not there.
	# modify them if they are there.
	$mesg = $ldap->search(
		base => "ou=MSG Groups,$domaindn",
		scope => "sub",
		filter => "(&(objectclass=msgGroup)(|(cn=Postmaster)(cn=MAILER-DAEMON)))",
		attrs => '*' );

	if ($mesg->code) {
		$ldap->unbind;
		print getLDAPerrorString("search", $mesg) . "\n";
		exit(1);
	}

	foreach $aliasentry ($mesg->all_entries) {
		$aliasdn = $aliasentry->dn;
		$aliascn = $aliasentry->get_value("cn");
		if ($aliascn eq "Postmaster") {
			$postmaster = 1;
		}
		if ($aliascn eq "MAILER-DAEMON") {
			$mailerdaemon = 1;
		}
		# change owner
		@ownerlist = $aliasentry->get_value("owner");
		for ($i = 0; $i < scalar(@ownerlist); $i++) {
			$item = $ownerlist[$i];
			if (substr($item, 0, 10) eq "uid=admin,") {
				$item = "uid=msguser,$ldapsuffix";
				$ownerlist[$i] = $item;
			}
		}
		# change member
		@memberlist = $aliasentry->get_value("member");
		for ($i = 0; $i < scalar(@ownerlist); $i++) {
			$item = $memberlist[$i];
			if (substr($item, 0, 10) eq "uid=admin,") {
				$item = "cn=MSG Administrators,$ldapsuffix";
				$memberlist[$i] = $item;
			}
		}
		%attrpairs = ();
		$attrpairs{"owner"} = \@ownerlist;
		$attrpairs{"member"} = \@memberlist;
		$attrpairs{"description"} = "$aliascn alias: cannot be deleted";
		$hashref = \%attrpairs;
		$mesg = $ldap->modify($aliasdn, replace => $hashref);
		if ($mesg->code) {
			$ldap->unbind;
			print getLDAPerrorString("modify", $mesg) . "\n";
			exit(1);
		}
	}
	# if the system aliases were not found, add them.
	if (!$postmaster) {
		$aliasdn = "cn=Postmaster,ou=MSG Groups,$domaindn";
		$aliasattrs = [
			objectClass => [ "top", "msgGroup" ],
			cn => "Postmaster",
			mail => "postmaster\@$vdomain",
			owner => "uid=msguser,$ldapsuffix",
			member => "cn=MSG Administrators,$ldapsuffix",
			"${msgldapprefix}MsgMgrpJoinable" => "FALSE",
			ou => "$vdomain",
			description => "Postmaster alias: cannot be deleted",
			];
		 
		$mesg = $ldap->add(
			dn => $aliasdn,
			attr => $aliasattrs);
		 
		if( $mesg->code ) {
			print getLDAPerrorString("add",$mesg) . "\n";
			$ldap->unbind;
			exit(1);
		}
	}
	if (!$mailerdaemon) {
		$aliasdn = "cn=MAILER-DAEMON,ou=MSG Groups,$domaindn";
		$aliasattrs = [
			objectClass => [ "top", "msgGroup" ],
			cn => "MAILER-DAEMON",
			mail => "MAILER-DAEMON\@$vdomain",
			owner => "uid=msguser,$ldapsuffix",
			member => "cn=MSG Administrators,$ldapsuffix",
			"${msgldapprefix}MsgMgrpJoinable" => "FALSE",
			ou => "$vdomain",
			description => "MAILER-DAEMON alias: cannot be deleted",
			];
		 
		$mesg = $ldap->add(
			dn => $aliasdn,
			attr => $aliasattrs);
		 
		if( $mesg->code ) {
			print getLDAPerrorString("add",$mesg) . "\n";
			$ldap->unbind;
			exit(1);
		}
	}
}

# add stuff to all users in the given domain
sub
do_users
{
	my ($domaindn) = @_;
	my ($mesg, $userentry, $userdn, %attrpairs, $hashref);
	my $vdomain = getfirstfromdn($domaindn);

	# get all the users and update them one at a time.
	$mesg = $ldap->search(
		base => "ou=MSG Users,$domaindn",
		scope => "sub",
		filter => "(objectclass=msgUser)",
		attrs => '*' );

	if ($mesg->code) {
		$ldap->unbind;
		print getLDAPerrorString("search", $mesg) . "\n";
		exit(1);
	}

	foreach $userentry ($mesg->all_entries) {
		$userdn = $userentry->dn;
		%attrpairs = ();
		@vals = $userentry->get_value("${msgldapprefix}MsgForwardCopy");
		if (scalar(@vals)) {
			$attrpairs{"${msgldapprefix}MsgForwardCopy"} = $vals[0];
		} else {
			$attrpairs{"${msgldapprefix}MsgForwardCopy"} = "FALSE";
		}
		@vals = $userentry->get_value("${msgldapprefix}MsgVacationEnabled");
		if (scalar(@vals)) {
			$attrpairs{"${msgldapprefix}MsgVacationEnabled"} = $vals[0];
		} else {
			$attrpairs{"${msgldapprefix}MsgVacationEnabled"} = "FALSE";
		}
		@vals = $userentry->get_value("${msgldapprefix}MsgSpamFilterEnabled");
		if (scalar(@vals)) {
			$attrpairs{"${msgldapprefix}MsgSpamFilterEnabled"} = $vals[0];
		} else {
			$attrpairs{"${msgldapprefix}MsgSpamFilterEnabled"} = "FALSE";
		}
		@vals = $userentry->get_value("${msgldapprefix}MsgSpamDestroyEnabled");
		if (scalar(@vals)) {
			$attrpairs{"${msgldapprefix}MsgSpamDestroyEnabled"} = $vals[0];
		} else {
			$attrpairs{"${msgldapprefix}MsgSpamDestroyEnabled"} = "FALSE";
		}
		@vals = $userentry->get_value("${msgldapprefix}MsgQuotaLimit");
		if (scalar(@vals)) {
			$attrpairs{"${msgldapprefix}MsgQuotaLimit"} = $vals[0];
		} else {
			$attrpairs{"${msgldapprefix}MsgQuotaLimit"} = "NONE";
		}
		@vals = $userentry->get_value("${msgldapprefix}MsgDrop");
		if (scalar(@vals)) {
			if ($vals[0] eq '') {
				$attrpairs{"${msgldapprefix}MsgDrop"} = $vals[0];
			} elsif ($vals[0] =~ /@/) {
				$attrpairs{"${msgldapprefix}MsgDrop"} = $vals[0];
			} else {
				$attrpairs{"${msgldapprefix}MsgDrop"} = $vals[0] . '@' . $vdomain;
			}
		} else {
			$attrpairs{"${msgldapprefix}MsgDrop"} = '';
		}

		$hashref = \%attrpairs;
		$mesg = $ldap->modify($userdn, replace => $hashref);
		if ($mesg->code) {
			$ldap->unbind;
			print getLDAPerrorString("modify", $mesg) . "\n";
			exit(1);
		}
	}
}

# bind to ldap, update all the objects we care about through LDAP.
sub
update_ldap
{
	my ($result, $mesg, $serverentry, $serverdn, %attrpairs, $hashref);
	my ($domainentry, $domaindn);

	$ldap = Net::LDAP->new("localhost") || die "Unable to create LDAP object";
	$result = $ldap->bind("$rootdn", password => "$rootpw", version => 3);
	if ($result->code) {
		print getLDAPerrorString("bind", $result) . "\n";
		exit(1);
	}

	# update the server object

	$mesg = $ldap->search(
		base => $ldapsuffix,
		scope => "base",
		filter => "(objectclass=msgServer)",
		attrs => '*' );

	if ($mesg->code) {
		$ldap->unbind;
		print getLDAPerrorString("search", $mesg) . "\n";
		exit(1);
	}

	$serverentry = $mesg->entry(0);
	if (!$serverentry) {
		$ldap->unbind;
		print(STDERR "server entry not found\n");
		exit(1);
	}
	$serverdn = $serverentry->dn;

	# our list of things to modify
	%attrpairs = ();
	$attrpairs{"${msgldapprefix}MsgServerVersion"} = "$msgversion";
	$attrpairs{"${msgldapprefix}MsgSchemaVersion"} = "$msgschemaversion";
	$attrpairs{"${msgldapprefix}MsgEnableRblLookups"} = "FALSE";
	$attrpairs{"${msgldapprefix}MsgAllowUserEmbedAlias"} = "FALSE";
	$attrpairs{"${msgldapprefix}MsgAllowUserRemoteWrite"} = "TRUE";
	$attrpairs{"${msgldapprefix}MsgAllowUserForwardWrite"} = "TRUE";
	$attrpairs{"${msgldapprefix}MsgAllowUserVacationWrite"} = "TRUE";
	$attrpairs{"${msgldapprefix}MsgAllowUserSpamWrite"} = "TRUE";
	$attrpairs{"${msgldapprefix}MsgDefaultQuotaLimit"} = "NONE";
	$attrpairs{"${msgldapprefix}MsgRblMember"} = [ "blackholes.mail-abuse.org" ];

	$hashref = \%attrpairs;
	$mesg = $ldap->modify($serverdn, replace => $hashref);
	if ($mesg->code) {
		$ldap->unbind;
		print getLDAPerrorString("modify", $mesg) . "\n";
		exit(1);
	}

	# Update all domains and the two system aliases underneath them.
	$mesg = $ldap->search(
		base => $ldapsuffix,
		scope => "one",
		filter => "(objectclass=organizationalUnit)",
		attrs => [ 'dn', 'objectclass', 'description' ] );

	if ($mesg->code) {
		$ldap->unbind;
		print getLDAPerrorString("search", $mesg) . "\n";
		exit(1);
	}

	foreach $domainentry ($mesg->all_entries) {
		$domaindn = $domainentry->dn;

		%attrpairs = ();
		$attrpairs{"objectclass"} = [ 'top', 'organizationalUnit', 'msgDomain' ];
		$hashref = \%attrpairs;
		$mesg = $ldap->modify($domaindn, replace => $hashref);
		if ($mesg->code) {
			$ldap->unbind;
			print getLDAPerrorString("modify", $mesg) . "\n";
			exit(1);
		}
		# do the aliases
		do_aliases($domaindn);
		do_users($domaindn);
	}

	$ldap->unbind;
}

# add ACLs at this point
sub
update_slapconf
{
	my ($ndx, $line, @arr, $newtext, @new, $i, $idx);

$newtext = "access to attr=${msgldapprefix}MsgMgrpRFC822Member
	by group.exact=\"cn=MSG Administrators,$ldapsuffix\" write
	by dnattr=owner write
	by users read
	by anonymous read

access to attr=${msgldapprefix}MsgForwardingAddress
	by group.exact=\"cn=MSG Administrators,$ldapsuffix\" write
	by self write
	by users none
	by anonymous read

access to attr=${msgldapprefix}MsgVacationEnabled
	by group.exact=\"cn=MSG Administrators,$ldapsuffix\" write
	by self write
	by users none
	by anonymous read

access to attr=${msgldapprefix}MsgSpamFilterEnabled
	by group.exact=\"cn=MSG Administrators,$ldapsuffix\" write
	by self write
	by users none
	by anonymous read

access to attr=${msgldapprefix}MsgQuotaLimit
	by group.exact=\"cn=MSG Administrators,$ldapsuffix\" write
	by self read
	by users none
	by anonymous read

";

	open(FD, "$slapconf") || die "Unable to read $slapconf";
	@slapfile = <FD>;
	close(FD);

	for ($ndx = 0; $ndx < scalar(@slapfile); $ndx++) {
		$line = $slapfile[$ndx];
		# check they are not already there
		if ($line =~ /^access to attr=${msgldapprefix}MsgMgrpRFC822Member/) {
			return;
		}
		# insert our new ACLs before this line.
		if ($line =~ /^access to filter="\(objectclass=msgGroup\)"/) {
			@new = $newtext;
			splice(@slapfile, $ndx, 0, @new);
			last;
		}
	}

	open(FD, ">$slapconf") || die "Unable to write $slapconf";
	foreach $line (@slapfile) {
		print FD $line;
	}
	close(FD);
}

# imapd.conf tends to overwrite the existing one, needing a reconfig
sub
update_imap
{
	my ($ndx, $line, @arr);

	open(FD, "$imapconf") || die "Unable to read $imapconf";
	@imapfile = <FD>;
	close(FD);

	for ($ndx = 0; $ndx < scalar(@imapfile); $ndx++) {
		$line = $imapfile[$ndx];
		if ($line =~ /\%ADMIN\%/) {
			$line =~ s/\%ADMIN\%/$msgadmin/;
			$imapfile[$ndx] = $line;
		}
	}

	open(FD, ">$imapconf") || die "Unable to write $imapconf";
	foreach $line (@imapfile) {
		print FD $line;
	}
	close(FD);
}

# MAIN Main main

parse_conf noauth;

$rootpw = mkpwd();

slapd_in();

update_ldap();
update_slapconf();

slapd_out();

update_imap();
