#{{PERL-EXEC}}
#
#
# Copyright 2003 Sun Microsystems, Inc. All Rights Reserved
# Patents Pending.Use is subject to license terms.
#


sub getNewCSN
{
   local ($replicaid) = @_;
   
   if (! $replicaid) {
     $replicaid = "0000";
   }

   my $newtime = sprintf("%08x", time);
   my $newseq = "0000";
   my $newsubseq = "0000";

   $newcsn = sprintf("%s%s%s%s", $newtime, $newseq, $replicaid, $newsubseq);
   return $newcsn;
}


$SCHEMADIR = "{{MY-DS-ROOT}}{{SEP}}config{{SEP}}schema";
$file = "";
$userfile= "";

#change the directory
chdir($SCHEMADIR);


opendir(DIR, '.');
@files = sort grep(/.*ldif$/,readdir(DIR));

foreach $file (@files) {
 $userfile = $file;
}


$old = $userfile;
$new = "$userfile.tmp.$$";
$bak = "$userfile.bak";
$find = 0;

open( LDIFFILE, "< $userfile" ) || die "\nCan't open $userfile \n";
open( NEW, "> $new" )    || die "\nCan't open $new \n";

$newcsn = getNewCSN($oldrid);
    
while (<LDIFFILE>) {
  
  if (/^nsSchemaCSN: ([0-9a-fA-F]+)/) {
    $find =1;
    $oldcsn = $1; 
    $oldrid = substr($oldcsn, 12, 4);
    
    $newcsn = getNewCSN($oldrid);
    
# If the oldest csn present into the file is greater than
# the new csn computed, just use the oldest with 
# seq num +1

    if ($oldcsn ge $newcsn) {
      $oldtime = substr($oldcsn, 0, 8);
      $oldseq = substr($oldcsn, 8, 4);
      $newseq = sprintf("%04x", hex($oldseq) + 1);
      $newsubseq = "0000"; 
      $newcsn = sprintf("%s%s%s%s", $oldtime, 
			$newseq, $oldrid, $newsubseq);
    }

    s/^nsSchemaCSN: ([0-9a-fA-F]+)/nsSchemaCSN: $newcsn/i;
    print NEW $_ or die "Can't write to $new: $! \n";
    
  }
  else {
    if ($_ !~ /^$/) {
      print NEW;
    }
  }

}

if (!$find){
  print NEW "nsSchemaCSN: $newcsn\n" or die "Can't write to $new: $! \n";
}

print NEW "\n";

print STDOUT "Restart your Directory Server";
print STDOUT " to take into account the schema modification\n\n";


close(LDIFFILE);
close(NEW);

rename($old, $bak)          or die "can't rename $old to $bak: $!";
rename($new, $old)          or die "can't rename $new to $old: $!";

closedir(DIR);


