#!/usr/bin/perl
#
# Copyright (C) 2001 Caldera International, Inc.  All Rights Reserved.
#
# domainmove
#
# change name of a domain
# really means create the new domain,
# recursively move all the objects in the old domain to the new domain,
# and delete the old domain.
# aliases must have their references changed to match the new domain name.
#
# If the primary domain is being moved
# the references to the admin user must be modified in:
#	/etc/opt/lsb*/msg/msg.conf
#	and in the admin group
# I use our domaincreate/domaindelete twins for the postfix part.
#
# This is a big job if there are lots of users or aliases.
# It is restartable from interruption by
# using the --exists directive.
#
# this script currently cannot cope with more than one admin
# user in the group MSG Administrators although some code segments
# do cope with more than one.

$DEBUG	= 0;				# must be first statement

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

use 		msglib;

sub Usage {
	print STDERR msgi18nmsg(1); # usage messsage
        exit(1);
}

# lots of global variable dependencies in this routine so be careful
# notable is the admin hash table.
sub moveentry {
	my ($entry) = @_;

	$olddn = $entry->dn;
	$newdn = $olddn;
	$newdn =~ s/ou=$domain,/ou=$newdomain,/;

	# if admin we have to add the new administrator to the group first
	# so we don't lose priviledges.
	if (exists($adminhash{$olddn})) {
		# update our internal idea of who admins are
		$msgadmindn = $newdn;

		# build list and send to ldap server
		$newadmins = [ $msgadmindn, $oldadmindn ];
		$newhash{"member"} = $newadmins;
		$mesg = $ldap->modify($admingrpdn, replace => \%newhash);
		if ($mesg->code) {
			print getLDAPerrorString("modify",$mesg) . "\n";
			$ldap->unbind;
			exit(1);
		}
	}

	%attrpairs = ();
	foreach $attr ($entry->attributes) {
		@arr = $entry->get_value($attr);
		# fixup a few of these from the old to new domain
		if ($attr eq "mail") {
			$arr[0] =~ s/\@$domain$/\@$newdomain/;
		}
		if ($attr eq "ou") {
			$arr[0] =~ s/$domain/$newdomain/;
		}
		if ($attr eq "${msgldapprefix}MsgAlternateAddress") {
			$arr[0] =~ s/\@$domain$/\@$newdomain/;
		}
		if ($attr eq "member") {
			$arr[0] =~ s/ou=$domain,/ou=$newdomain,/;
		}
		if ($attr eq "owner") {
			$arr[0] =~ s/ou=$domain,/ou=$newdomain,/;
		}
		if ($attr eq "${msgldapprefix}MsgDrop") {
			$arr[0] =~ s/\@$domain$/\@$newdomain/;
		}
		if (scalar(@arr) > 1) {
			$attrpairs{"$attr"} = [ @arr ];
			$val = $attrpairs{"$attr"};
		} else {
			$attrpairs{"$attr"} = $arr[0];
		}
	}
	# ok delete the old one and create the new one.
	$attrlist = "";
	foreach $attr (keys(%attrpairs)) {
		$val = $attrpairs{"$attr"};
		$attrlist = [ @$attrlist, $attr => $val ];
	}
	$mesg = $ldap->delete($olddn);
	if ($mesg->code) {
		print getLDAPerrorString("delete",$mesg) . "\n";
		$ldap->unbind;
		exit(1);
	}
	# if add fails because the object already exists it is ok
	# this can only really happen with alias name clashes.
	$mesg = $ldap->add(
		dn => $newdn,
		attr => $attrlist);
	if ($mesg->code) {
		$name = ldap_error_name($mesg->code);
		if ($name ne "LDAP_ALREADY_EXISTS") {
			print getLDAPerrorString("add",$mesg) . "\n";
			$ldap->unbind;
			exit(1);
		}
		if (!$quiet) {
			if (exists($attrpairs{uid})) {
				print msgi18nmsg(8, $attrpairs{uid}); # uid %1 exists in both domains, --newdomain one is preserved
			} else {
				print msgi18nmsg(9, $attrpairs{cn}); # alias %1 exists in both domains, --newdomain one is preserved
			}
		}
	} elsif (!$quiet) {
		if (exists($attrpairs{uid})) {
			print msgi18nmsg(10, $attrpairs{uid}); # moved uid:%1
		} else {
			print msgi18nmsg(11, $attrpairs{cn}); # moved alias:%1
		}
	}
}

#
# main
#

msgi18ninit(38); # set 38 is msgdomainmove

$argc = @ARGV;
if ($argc < 1) {
	Usage();
}

$exists = 0;
$quiet = 0;

foreach (@ARGV) {
	if (/^--/) {
		chomp($_);
		@optarg = split('=', $_, 2);
                $attr    = $optarg[0];
                $attr    =~ s/^--//;
		$val = $optarg[1];
		if ("$attr" eq "") {
			Usage;
		}
		argcheck($attr, $val);
		if ($val eq "") {
			if ($attr eq "quiet") {  
				$quiet = 1;
			} elsif ($attr eq "exists") {  
				$exists = 1;
			} elsif ($attr eq "description") {  
				# have to set a flag so that null description works
				$newdescription = $val;
				$descriptionchanged = 1;
			} else {
				Usage;
			}
			next;
		}
                if ($attr eq "olddomain") {  
			$domain = $val;
                } elsif ($attr eq "newdomain") {  
			$newdomain = $val;
                } elsif ($attr eq "description") {  
			$newdescription = $val;
			$descriptionchanged = 1;
		} else {
			Usage;
		}
	} else {
		Usage;
	}
}

if (!$domain || !$newdomain) {
	Usage();
}

# Get defaults for LDAP
parse_conf;

# connect to LDAP
$ldap   = Net::LDAP->new($ldaphost) or die msgi18nmsg(2) . "$@";
$result = $ldap->bind("$msgadmindn", password => "$msgadminpw", version => 3);

if ($result->code) {
	print getLDAPerrorString("bind",$result) . "\n";
	exit(1);
}

# fetch the source domain
$mesg = $ldap->search(base => $ldapsuffix,
	      scope => "one", 
	      filter => fbuild("(&(objectclass=msgDomain)(ou=%1))", $domain),
	      attrs => ['dn', 'description']);

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

if (!$mesg->count) {
	print STDERR msgi18nmsg(3, $domain); # --domain=$domain does not exist
	$ldap->unbind;
	exit(1);
}

$entry = $mesg->entry(0);
$domaindn = $entry->dn;
$description = $entry->get_value("description");
if ($descriptionchanged) {
	$description = $newdescription;
}

# now fetch our admin group
$mesg = $ldap->search(base => $ldapsuffix,
	      scope => "one", 
	      filter => fbuild("(&(objectclass=groupOfNames)(cn=MSG Administrators))"),
	      attrs => ['dn', 'member']);

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

if (!$mesg->count) {
	print STDERR msgi18nmsg(4); # cannot find administrators group
	$ldap->unbind;
	exit(1);
}

$adminentry = $mesg->entry(0);

# make a hash of the administrators so we can update easily later.
@administrators = $adminentry->get_value("member");
$admingrpdn = $adminentry->dn;
foreach $admin (@administrators) {
	$adminhash{$admin} = "TRUE";
}

# check if target domain exists.
$mesg = $ldap->search(base => $ldapsuffix,
	      scope => "one", 
	      filter => fbuild("(ou=%1)", $newdomain),
	      attrs => ['dn', 'description', 'objectclass']);

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

# must be msgdomain type
if ($mesg->count) {
	$entry = $mesg->entry(0);
	@objectclass = $entry->get_value("objectclass");
	foreach $class (@objectclass) {
		if ($class =~ /msgdomain/i) {
			$found = 1;
		}
	}

	if (!$found) {
		print STDERR msgi18nmsg(15, $newdomain); # reserved name
		$ldap->unbind;
		exit(1);
	}
}

if ($mesg->count) {
	if (!$exists) {
		print STDERR msgi18nmsg(5, $newdomain); # Target domain exists, use --exists to merge domains
		$ldap->unbind;
		exit(1);
	}
	if (!$quiet) {
		print msgi18nmsg(6, $newdomain); # Target domain exists, merging domains
	}
} else {
	# create the new domain
	if (!$quiet) {
		print msgi18nmsg(7, $newdomain); # creating domain $newdomain
	}
	$cmd = "|$msgbin/msgdomaincreate --domain=$newdomain";
	if ($description) {
		$cmd = "$cmd \"--description=$description\"";
	}
	if (!do_cmd($cmd)) {
		exit(1);
	}
}

# now move the users one at a time, check if in admin cache for each one.
# this takes a long time if lots of users.
$searchdn = $domaindn;
$mesg = $ldap->search(base => $searchdn,
	      scope => "sub", 
	      filter => fbuild("(|(objectclass=msgUser)(objectclass=msgGroup))"),
	      attrs => ['*']);

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

$oldadmindn = $msgadmindn;
# the main move loop
if ($mesg->count) {
	# got some users or aliases,
	# change their dn, put them back and delete the old ones
	$adminuserentry = 0;
	foreach $entry ($mesg->entries) {
		if ($entry->dn eq $msgadmindn) {
			$adminuserentry = $entry;
		} else {
			moveentry($entry);
		}
	}
	# do admin user last to preserve restartability in the master domain
	if ($adminuserentry) {
		moveentry($adminuserentry);
	}
}

# to avoid race conditions, query the ladp server to determine
# if destination domain contains the administrator user.
# if so then update msg.conf
$searchdn = $newdn;
$mesg = $ldap->search(base => $searchdn,
	      scope => "sub", 
	      filter => fbuild("(uid=admin)"),
	      attrs => ['dn']);

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

# change the admin user references as needed, only in master domain today
if ($mesg->count) {
	# now msg.conf, the admin dn changes from olddomain to newdomain.
	$ret = do_rootread("$msgetcdir/msg.conf", \@lines);
	if ($ret == 0) {
		print STDERR msgi18nmsg(12, "msg.conf"); # Cannot read msg.conf
		exit(1);
	}
	for ($i = 0; $i < scalar(@lines); $i++) {
		$line = $lines[$i];
		if ($line =~ m/^ADMINDN:/) {
			$line =~ s/ou=$domain,/ou=$newdomain,/;
			$lines[$i] = $line;
		}
	}
	$ret = do_rootwrite("$msgetcdir/msg.conf", \@lines);
	if ($ret == 0) {
		print STDERR msgi18nmsg(13, "msg.conf"); # Cannot write msg.conf
		exit(1);
	}
	# delete the old admin group entry by keeping only the current one
	$newadmins = [ $msgadmindn ];
	$newhash{"member"} = $newadmins;
	$mesg = $ldap->modify($admingrpdn, replace => \%newhash);
	if ($mesg->code) {
		print getLDAPerrorString("modify",$mesg) . "\n";
		$ldap->unbind;
		exit(1);
	}
}

# delete the old domain
if (!$quiet) {
	print msgi18nmsg(14, $domain); # deleting domain $domain
}
$cmd = "|$msgbin/msgdomaindelete --domain=$domain";
if (!do_cmd($cmd)) {
	exit(1);
}

$ldap->unbind;

exit(0);
