#!/bin/sh
#
# Author: Jesus Perez 
# Pragma: Nov 30 2001  vers. 1.0 
#
# This is to replicate LDAPs as a mechanism to synchronize contents as all are active.
# The idea is:
#   In case this script is running on the Master to replicate ...
#   1)  to generate "ldif" files from the "primary" LDAPs 
#   2)  to send it to the "secondary" LDAPs
#   In case this script is running on a target LDAP ...
#   1)  Re-load inf if there is info available i
#       (so just in case of paranoia it can be run form system cron)
#
# some criteria can be changed ...
# the LDAP commands, etc are for IPLANET 
#
masterHost=rstmco1-82
#masterHost=alhambra
targetHost=rstmco1-81
targetHost=alhambra

ldapHome=/opt/netscape/ldap
masterDirs="slapd-ttaldap slapd-ttacache"
ldifcmd=db2ldif
ldif2dbcmd=ldif2db
ldapStop=stop-slapd
ldapStart=start-slapd
workingDir=/opt/save/toreplicate
workingDir2=/opt/save/toreplicate2
saveReplica=/opt/save/replicas

loginToSend=rima
passwToSend=tde2001
serviceToSend=ftp

ahora=`date +%Y_%m_%d_%H%M%S` 
thisHost=`hostname` 


if [ "$thisHost" == "$masterHost" ]
then
 
   for ldap in ` echo $masterDirs` 
   do
      nom=`echo $ldap | sed 's/slapd-//g'` 
      file=$nom"_"$ahora
      $ldapHome/$ldap/$ldifcmd $workingDir/$file
   done

   if [ "$serviceToSend" == "ftp" ]
   then 

         wkFtp=$workingDir/ftp.$$
         echo "" >$wkFtp
         echo "user $loginToSend $passwToSend ">>$wkFtp
         echo "binary ">>$wkFtp
         echo "prompt">>$wkFtp
         echo "cd $workingDir2 ">>$wkFtp
         echo "lcd $workingDir"  >>$wkFtp
         echo "mput *$ahora"  >>$wkFtp
         echo "bye " >>$wkFtp
         for server in `echo $targetHost` 
         do
             ftp -n $server  <$wkFtp
             result=$?
         done
         [ "$result" = "0" ] && {
              mv $workingDir/*$ahora $saveReplica
              echo $ahora >$saveReplica/last_send
              touch $saveReplica/last_send
         }
         rm $wkFtp
   fi
else

   for ldap in ` echo $masterDirs` 
   do
      nom=`echo $ldap | sed 's/slapd-//g'` 
      file=$nom"_"$ahora

      # Stoping LDAP server
      $ldapHome/$ldap/$ldapStop

      # Loading  LDAP server
      templateFiles=$workingDir/$nom"_*" 
      for ldif_file in `ls $templateFiles` 
      do
          chmod 777 $ldif_file
          # This is just for IPLANET
          dirLoad=`basename $ldif_file | sed "s,$nom,,g" | sed 's/^_*//g' `
          mkdir $saveReplica/$dirLoad 2>/dev/null 
          nload=$saveReplica/$dirLoad/$nom"_load"
          echo "Loading .... $nom ... from  `basename $ldif_file ` ..."
          $ldapHome/$ldap/$ldif2dbcmd -i $ldif_file >$nload 
          [ "$?" = "0" ] && {
              mv $ldif_file $saveReplica/$dirLoad
              touch $nload
          }
      done
      # Starting LDAP server
      $ldapHome/$ldap/$ldapStart
   done
fi


