#!/bin/ksh

# Copyright  2004 Sun Microsystems, Inc. All rights reserved. 
# 
# Sun Microsystems, Inc. has intellectual property rights relating to
# technology embodied in the product that is described in this document.
# In particular, and without limitation, these intellectual property rights
# may include one or more of the U.S. patents listed at
# http://www.sun.com/patents and one or more additional patents or pending
# patent applications in the U.S. and in other countries.
# 
# U.S. Government Rights - Commercial software. Government users are subject
# to the Sun Microsystems, Inc. standard license agreement and applicable
# provisions of the FAR and its supplements.
# 
# Use is subject to license terms. 
# 
# This distribution may include materials developed by third parties. Sun,
# Sun Microsystems, the Sun logo, Java and Sun[tm] ONE are trademarks or
# registered trademarks of Sun Microsystems, Inc. in the U.S. and other
# countries. 
# 
# Copyright  2004 Sun Microsystems, Inc. Tous droits rservs. Sun
# Microsystems, Inc. dtient les droits de proprit intellectuels relatifs
#  la technologie incorpore dans le produit qui est dcrit dans ce document.
# En particulier, et ce sans limitation, ces droits de proprit
# intellectuelle peuvent inclure un ou plus des brevets amricains lists
#  l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires
# ou les applications de brevet en attente aux Etats - Unis et dans les
# autres pays.
# 
# L'utilisation est soumise aux termes du contrat de licence.
# 
# Cette distribution peut comprendre des composants dvelopps par des
# tierces parties.
# 
# Sun, Sun Microsystems, le logo Sun, Java et Sun[tm] ONE sont des marques
# de fabrique ou des marques dposes de Sun Microsystems, Inc. aux
# Etats-Unis et dans d'autres pays.


  BASE=BASEDIR
  LDAPDIR=${LDAP_DIR}
  PRODUCTDIR=${PRODUCT_DIR}
  PACKAGEDIR=$BASE/$PRODUCTDIR

  PLATFORMCONFDIR=IS_INSTALL_ETCDIR/IS_PRODNAME/config
  PLATFORMCONF=$PLATFORMCONFDIR/AMConfig.properties
  VERSIONFILE=IS_INSTALL_ETCDIR/IS_PRODNAME/config/.version

  WS_LOCATION=WS_BASE_DIR

  NES_SERVER="$WS_LOCATION/https-WEBSERVER_HOST"
  NES_ADM="$WS_LOCATION/https-admserv"

  ECHO=/usr/bin/echo

  LDAPMODIFY=$PACKAGEDIR/bin/ldapmodify
  LDAPSEARCH=$PACKAGEDIR/bin/ldapsearch
  LDAP_LIBRARY_PATH=$PACKAGEDIR/ldaplib/ldapsdk  
  
  LN=/usr/bin/ln
  S1ASINSTANCEDIR=SUNAPPSERVER_INSTANCE_DIR_TAG
  WEBCONTAINER=WEB_CONTAINER_TAG
  
  WEBLOGIC_DIR=WL61_PROD_DIR
  WEBLOGIC_DOMAIN=WL61_DOMAIN

  WEBSPHERE_DIR=WAS40_BASE

  SYS_OWNER=NEW_OWNER
  SYS_GROUP=NEW_GROUP

########################################

	# i18n 
	gettext=/usr/bin/gettext

        TEXTDOMAIN=backup_restore
        TEXTDOMAINDIR=${PACKAGEDIR}/locale

        export TEXTDOMAIN
        export TEXTDOMAINDIR
        export LANG

########################################
	
	#test for root user
	#
	check_root_user() 
	  {
	  uid=`/usr/xpg4/bin/id -un`
	  if [[ "$uid" != "root" && "$uid" != $SYS_OWNER ]]; then
		$ECHO "`$gettext 'You must be either root user or the system user to run'` $0."
	    exit 1
	  fi
	  }

        # get the location of the directory server installation
        get_ds_location()
          {
            valid_ds_location="no"
            obtained_ds_location="yes"
            while [ "$valid_ds_location" = "no" ]; do
                print "\a`$gettext 'Enter directory server installation directory...enter $ for remote installation'`"
                read ds_location
                if [ "$ds_location" = "$" ]; then
                  return 1
                fi
                check_for_invalid_chars $ds_location
                if [[ $? = 0 && -d $ds_location ]]; then
                  valid_ds_location="yes"
                  return 0
                else
                  print "\a`$gettext 'Invalid response!'`"
                fi
            done

          }

	
	# check ds is local and configured for Identity Server
	check_for_ds() 
	  {
	  if [ -d $ds_old_location ]; then
            ds_location=$ds_old_location
	    ds="yes"
 	  elif [ "$obtained_ds_location" != "yes" ]; then
       	    $ECHO "`$gettext 'Either DS location has been changed or Directory instance is not present'`"
            get_ds_location
            if [ "$valid_ds_location" = "yes" ]; then
	      ds="yes"
            else
	      ds="no"
            fi
	  fi
          }

        # start ds
        start_ds()
          {
          $ds_location/start-slapd > /dev/null 2>&1
          }

	# Check for running ds
	check_for_running_ds() 
	  {
	  pid=`/usr/bin/ps -ef | /usr/bin/grep ns-slapd | /usr/bin/grep "$ds_location -i" | /usr/bin/awk '{ printf "%s", $2 }'`

	  if [ "$pid" != "" ]; then
	    running_ds="yes"
	  else
	    running_ds="no"
	  fi
	  }
	
	# stop ds 
	stop_ds() 
	  {
	  check_for_ds
	  if [ "$ds" = "no" ]; then
  	    return
  	  fi

 	  $ds_location/stop-slapd > /dev/null 2>&1
	  check_for_running_ds
	  if [ "$running_ds" = "yes" ]; then
  		do_cleanup
		$ECHO "`$gettext 'Can not stop DS : exiting !!'`"
		exit 1
	  fi
	  }

	# Check for running ws
    check_for_running_ws()
      {
      pid=`/usr/bin/ps -ef | /usr/bin/grep ns-httpd | /usr/bin/grep "$NES_SERVER" | /usr/bin/awk '{ printf "%s", $2 }'`
      if [ "$pid" != "" ]; then
        running_ws="yes"
      else
        running_ws="no"
      fi
      }

    # Check for running am
    check_for_running_am()
      {
      running_am="no"
      check_for_running_ws
      if [ "$running_ws" = "yes" ]; then
        running_am="yes"
      fi
      }
	
	# Check for the invalid characters
	check_for_invalid_chars() 
	  {
  	  if [[ $1 = +([/_.[:alnum:]-]) ]]; then
      	    return 0
  	  else
      	    return 1
 	  fi
	  }

	# Yes-no function	
	yesno() 
	  {
  	  ok="no"

  	  question=$1
 	  default=$2

  	  valids="ynYN"

  	  while [ "$ok" = "no" ]; do
        if [ "$default" = "y" ] || [ "$default" = "Y" ]
        then
    	  $ECHO "$question [y]/n \c"
      	  default="y"
    	elif [ "$default" = "n" ] || [ "$default" = "N" ]
   	    then
   		  $ECHO "$question y/[n] \c"
      	  default="n"
     	else
   		  $ECHO "$question y/[n] \c"
      	  default="n"
     	fi

    	read ans
	
    	if [ "$ans" = "" ]; then
          if [ "$default" != "" ]; then
	  	  	ans=$default
		  fi
    	fi

  	    if [ "$ans" = "`$gettext 'n'`" ]; then
          ok="yes"
        elif [ "$ans" = "`$gettext 'N'`" ]; then
          ok="yes"
        elif [ "$ans" = "`$gettext 'y'`" ]; then
          ok="yes"
        elif [ "$ans" = "`$gettext 'Y'`" ]; then
          ok="yes"
        fi

      	if [ "$ok" = "no" ]; then
	      print
		  print "\a`$gettext 'Invalid response!'`"
		  print
	    fi
      
	  done

	  # make sure we have a std response so client doesn't need to check
      if [ "$ans" = "`$gettext 'Y'`" ]; then
        ans="`$gettext 'y'"
      elif [ "$ans" = "`$gettext 'N'`" ]; then
        ans="`$gettext 'n'"
      fi
 	  }

	# display help
	display_help()
	  {
	  display_usage
	  $ECHO 
	  $ECHO "`$gettext 'Where:'`"
  	  $ECHO "`$gettext '    tar.gz-file		backup file-name in tar.gz format with full path(if path not given <install-dir/backup will be assumed)'`"
  	  $ECHO "`$gettext '    tar-file		backup file-name in tar format with full path(if path not given <install-dir/backup will be assumed)'`"
	  $ECHO 
	  $ECHO "`$gettext 'Options:'`"
  	  $ECHO "`$gettext '    -v or --verbose 	run in verbose mode'`"
	  }

	# display usage
	display_usage()
	  {
	  $ECHO "`$gettext 'Usage:'`"
  	  $ECHO "`$gettext '   ' `$0 [ -v | --verbose ]  -z | --gzip <tar.gz-file> or -t | --tar <tar-file>"
  	  $ECHO "`$gettext '   ' `$0 -h | --help"
  	  $ECHO "`$gettext '   ' `$0 -n | --version"

	  }
	
	# do necessary cleanup before exiting
        do_cleanup()
          {
          if [ -f "$WORKFILE" ]; then
            rm -rf $WORKFILE
          fi
          if [ -e "$WORKDIR" ]; then
            rm -rf $WORKDIR
          fi
          }

	# copy and verbose
	copy_and_verbose()
	  {
	  SOURCE=$1
	  DESTINATION=$2
	  PRINTDEST="`dirname $DESTINATION`/`basename $SOURCE`"

	  if [ $VERBOSE -eq 1 ]; then 
	    $ECHO "`$gettext 'Restoring : '` $PRINTDEST"
	  fi
	  
	  cp -rp $SOURCE $DESTINATION
	  if [ $? -ne 0 ]; then
        COPY_ERROR=1
	    $ECHO "`$gettext 'Failed to restore: '` $PRINTDEST" 
	  else
	  	if [ $VERBOSE -eq 1 ]; then 
	      $ECHO "$PRINTDEST `$gettext ' restored..'`" 
	  	fi
	  fi
	  }
        
         #copy recursively without overwriting and verbose
         copy_recursive(){
              if [ -f $1 ]; then
                        cp -rp $1 $2
	                if [ $VERBOSE -eq 1 ]; then 
	                  $ECHO "`$gettext 'Restoring : '` $2"
	                fi
              else
               if [ ! -z "`/usr/bin/ls $1`" ]; then
                  for certfiles in `ls $1`
                  do
                    if [ -f $certfiles ]; then
                        copy_recursive $1/$certfiles $2/$certfiles
                    else
                        if [ ! -d $2 ]; then
                            mkdir -p $2
                        fi
                        copy_recursive $1/$certfiles $2/$certfiles
                    fi
                  done

               fi
              fi
          }	
	
	# restore config
	do_restore_config()
	  {
	  $ECHO "`$gettext 'Restoring Configuration...'`" 
	  COPY_ERROR=0

	  WORKCONFIGDIR=$WORKDIR/config
	  
	  # start restore
	  copy_and_verbose $WORKCONFIGDIR/IS_PRODNAME/config IS_INSTALL_ETCDIR/IS_PRODNAME/.
	  copy_and_verbose $WORKCONFIGDIR/IS_PRODNAME/locale $PACKAGEDIR/.

	  for props in `ls $WORKCONFIGDIR/IS_PRODNAME/lib/*.properties`
	  do
	    copy_and_verbose $props $PACKAGEDIR/lib/.
	  done

	  for bins in `ls $WORKCONFIGDIR/IS_PRODNAME/bin`
	  do
	  	copy_and_verbose $WORKCONFIGDIR/IS_PRODNAME/bin/$bins $PACKAGEDIR/bin/.
	  done

         
	 if [ $WEBCONTAINER = "IBM_WEBSPHERE" ]; then
	       copy_and_verbose $WORKCONFIGDIR/installedApps $WEBSPHERE_DIR/.
	       copy_and_verbose $WORKCONFIGDIR/plugin-cfg.xml $WEBSPHERE_DIR/config/.
	       copy_and_verbose $WORKCONFIGDIR/setupCmdLine.sh $WEBSPHERE_DIR/bin/.
	       copy_and_verbose $WORKCONFIGDIR/admin.config $WEBSPHERE_DIR/bin/.
	 else if [ $WEBCONTAINER = "BEA_WEBLOGIC" ]; then
	       if [ ! -e $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging ]; then
			copy_and_verbose $WORKCONFIGDIR/.wlstaging $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging
	       else
	 	        copy_and_verbose $WORKCONFIGDIR/.wlstaging/amcommon.war $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/.
	                copy_and_verbose $WORKCONFIGDIR/.wlstaging/amconsole.war $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/.
	                copy_and_verbose $WORKCONFIGDIR/.wlstaging/ampassword.war $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/.
	                copy_and_verbose $WORKCONFIGDIR/.wlstaging/amserver.war $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/.
		fi
               copy_and_verbose $WORKCONFIGDIR/IS_PRODNAME/web-apps $PACKAGEDIR/.

               copy_and_verbose $WORKCONFIGDIR/config.xml $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.
               copy_and_verbose $WORKCONFIGDIR/.java.login.config $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.
               copy_and_verbose $WORKCONFIGDIR/startManagedWebLogic.sh $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.
               copy_and_verbose $WORKCONFIGDIR/startWebLogic.sh $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.                              

         else if [ $WEBCONTAINER = "AS7" ]; then
             for applications in `ls $WORKCONFIGDIR/applications/j2ee-modules`
             do
                copy_and_verbose $WORKCONFIGDIR/applications/j2ee-modules/$applications $S1ASINSTANCEDIR/applications/j2ee-modules/.
             done             
              copy_and_verbose $WORKCONFIGDIR/server.xml $S1ASINSTANCEDIR/config/.
              copy_and_verbose $WORKCONFIGDIR/server.policy $S1ASINSTANCEDIR/config/.
          else if [ $WEBCONTAINER = "WS6" ]; then
             for servers in `ls $WORKCONFIGDIR/ws`
             do
	  	copy_and_verbose $WORKCONFIGDIR/ws/$servers $WS_LOCATION/.
             done
             copy_and_verbose $WORKCONFIGDIR/IS_PRODNAME/web-src $PACKAGEDIR/.
	  fi
         fi
        fi
	fi
	  if [ ! -f /etc/rc1.d/K03amserver ]; then
            $LN -s /etc/init.d/amserver /etc/rc1.d/K03amserver 
          fi
          if [ ! -f /etc/rc2.d/K03amserver ]; then
            $LN -s /etc/init.d/amserver /etc/rc2.d/K03amserver 
          fi
          if [ ! -f /etc/rc3.d/S86amserver ]; then
            $LN -s /etc/init.d/amserver /etc/rc3.d/S86amserver 
          fi

	  
	  if [ "$ds" = "yes" ]; then
	    copy_and_verbose $WORKCONFIGDIR/ldap-host/config/schema $ds_location/config/.
	    if [ "$ds_old_location" != "$ds_location" ]; then
	      sed -e "s;$ds_old_location;$ds_location;g" $WORKCONFIGDIR/ldap-host/config/dse.ldif > updated_dse.ldif
	      cp updated_dse.ldif $WORKCONFIGDIR/ldap-host/config/dse.ldif
	      rm updated_dse.ldif
	      copy_and_verbose $WORKCONFIGDIR/ldap-host/config/dse.ldif $ds_location/config/.
	    fi
	  else
	    $ECHO "`$gettext 'Remote Directory Server: will not restore DS configuration files'`"
	  fi
         serviceconfig_backup_key=`grep "serviceconfiguration.backup.key=" $BACKUPINF | sed -e "s/serviceconfiguration.backup.key=//"`
           if [ "$serviceconfig_backup_key" = "1" ]; then
             if [ "$ds_old_location" = "$" ]; then
              do_restore_serviceconfig
              return $?
             elif [ "$DS" != "1" ]; then
              start_ds
              do_restore_serviceconfig
              return $?
             fi
          fi
	  }
         
        # restoration of updated service configuration
	do_restore_serviceconfig() 
          {
          export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$LDAP_LIBRARY_PATH
          ldaphost=`grep "com.iplanet.am.directory.host=" $PLATFORMCONF | sed -e "s/com.iplanet.am.directory.host=//"`
          ldapport=`grep "com.iplanet.am.directory.port=" $PLATFORMCONF | sed -e "s/com.iplanet.am.directory.port=//"`
          rootsuffix=`grep "com.iplanet.am.rootsuffix=" $PLATFORMCONF | sed -e "s/com.iplanet.am.rootsuffix=//"`
          amadmin=`grep "com.sun.identity.authentication.super.user=" $PLATFORMCONF | sed -e "s/com.sun.identity.authentication.super.user=//"`

          faced_connection_error="no"
          $ECHO "" > am2bak_rejected_entries.ldif
          $LDAPSEARCH -h $ldaphost -p $ldapport -D "$amadmin" -w "$amadmin_password" -b "$rootsuffix" entrydn=ou=services,* 1>search_out 2>search_err
          if [ $? != 0 ]; then
            grep "Connection" search_err
            if [ $? = 0 ]; then
              print "\a`$gettext 'directory server is not running..please start it and press return when ready...'`"
              read Return
              faced_connection_error="yes"
            fi
          fi
          if [ "$faced_connection_error" = "yes" ]; then
            $LDAPSEARCH -h $ldaphost -p $ldapport -D "$amadmin" -w "$amadmin_password" -b "$rootsuffix" entrydn=ou=services,* 1>search_out 2>search_err
            if [ $? != 0 ]; then
              grep "Connection" search_err
              if [ $? = 0 ]; then
                print "\a`$gettext 'directory server was not restarted..service configuration backup not done...'`"
                rm search_err search_out
                return 1
              fi
            fi
            get_amadmin_password
            if [ $? = 1 ]; then
              print "\a`$gettext 'service configuration restore not done...'`"
              rm modify_err modify_out
              return 1
            fi
          else
            get_amadmin_password
            if [ $? = 1 ]; then
              print "\a`$gettext 'service configuration restore not done...'`"
              rm modify_err modify_out
              return 1
            fi
          fi
          $ECHO "" >  am2bak_rejected_entries.ldif
          $LDAPMODIFY -h $ldaphost -p $ldapport -D $amadmin -w $amadmin_password -a -f $WORKCONFIGDIR/updated_services.ldif -c -e am2bak_rejected_entries.ldif 1>/dev/null 2>&1
          cat am2bak_rejected_entries.ldif | awk ' {
                            if ( $0 ~ /^dn:/ ) {
                                start_cons = "true"
                                DN=$0  }
                            else {
                             if (start_cons == "true") {
                                if ( $0 ~ /^ / ) {
                                    len = length($0)
                                    required = substr($0,2,len-1)
                                    DN = DN required
                                 }
                                 else {
                                     start_cons = "false"
                                     start_print = "true"
                                 }
                            }
                            if ( start_print == "true" ) {
                                 print DN
                                 DN=""
                                 start_print = "false"
                            }
                           }
                          }' > am2bak_extracted_dn.ldif
          cat am2bak_extracted_dn.ldif | awk '{s[NR]=$0} END {for(i=NR;i>0;i--) { print s[i]}} ' > am2bak_reversed_dn.ldif
          cat am2bak_reversed_dn.ldif | awk '{ if ($1 ~ /^dn:/) { print $0; print "changetype:delete\n"; }}' > am2bak_delete_list.ldif  1>/dev/null 2>&1
          $LDAPMODIFY -h $ldaphost -p $ldapport -D $amadmin -w $amadmin_password -c -f am2bak_delete_list.ldif 1>/dev/null 2>&1
          $LDAPMODIFY -h $ldaphost -p $ldapport -D $amadmin -w $amadmin_password -a -c -f am2bak_rejected_entries.ldif 1>/dev/null 2>&1
          rm am2bak_rejected_entries.ldif am2bak_extracted_dn.ldif am2bak_reversed_dn.ldif am2bak_delete_list.ldif
	  return $?
	  }
	
	# restore debug
	do_restore_debug()
	  {
	  $ECHO "`$gettext 'Restoring debug files...'`" 
	  COPY_ERROR=0

	  DEBUGLOCATION=`grep "debug.location.key=" $BACKUPINF | sed -e "s/debug.location.key=//"`

	  WORKDEBUGDIR=$WORKDIR/debug
	  
	  if [ ! -e "$DEBUGLOCATION" ]; then
		copy_and_verbose $WORKDEBUGDIR $DEBUGLOCATION
	  else
	  for debugfiles in `ls $WORKDEBUGDIR/*`
	  do
	  	copy_and_verbose $debugfiles $DEBUGLOCATION/.
	  done
	  
	  fi
	  return $COPY_ERROR
	  }

	# restore log
	do_restore_log()
	  {
	  $ECHO "`$gettext 'Restoring log files...'`" 
	  COPY_ERROR=0
	  	  
	  LOGLOCATION=`grep "log.location.key=" $BACKUPINF | sed -e "s/log.location.key=//"`
	    
	  WORKLOGDIR=$WORKDIR/log
	  
	  if [ ! -e "$LOGLOCATION" ]; then
		copy_and_verbose $WORKLOGDIR/logs $LOGLOCATION
	  else
	  for logfiles in `ls $WORKLOGDIR/logs/*`
	  do
		copy_and_verbose $logfiles $LOGLOCATION/.
	  done
	  fi

	  if [ ! -e "/var/sadm/install/logs" ]; then
                copy_and_verbose $WORKLOGDIR/install /var/sadm/install/logs
          else 
            if [ ! -z "`/usr/bin/ls $WORKLOGDIR/install`" ]; then
            for logfiles in `ls $WORKLOGDIR/install/*`
            do
                 copy_and_verbose $logfiles /var/sadm/install/logs/.
            done
            fi
          fi
 
	  return $COPY_ERROR
	  }
	  
	# restore cert db
	do_restore_cert()
	  {
	  $ECHO "`$gettext 'Restoring cert db...'`"
	  COPY_ERROR=0
	  
          WORKCERTDIR=$WORKDIR/cert
          if [ ! -e $cert_location ]; then
            copy_and_verbose $WORKCERTDIR/cert $cert_location
          else
            copy_recursive $WORKCERTDIR/cert $cert_location
          fi
	  if [ "$ds" = "yes" ]; then
		if [ ! -e $ds_location/../alias ]; then 
		  copy_and_verbose $WORKCERTDIR/ds/alias $ds_location/../.
	        else	
		  if [ ! -z "`/usr/bin/ls $WORKCERTDIR/ds/alias`" ]; then
		  for dscertfiles in `ls $WORKCERTDIR/ds/alias/*`
		  do
		    copy_and_verbose $dscertfiles $ds_location/../alias/.
		  done
		  fi
		fi
	  fi
	  
	  return $COPY_ERROR
	  }
	  
	# restore ds
	do_restore_ds()
	  {
	  if [ "$ds" = "yes" ]; then
	    $ECHO "`$gettext 'Restoring Directory server...'`" 
	    
	    WORKDSDIR=$WORKDIR/ds
	    LDIF_FILE=`basename $WORKDIR`
	    LDIF_FILE=$LDIF_FILE.ldif
	    
	    rootsuffix=`grep "com.iplanet.am.rootsuffix=" $PLATFORMCONF  | sed -e "s/com.iplanet.am.rootsuffix=//"`
	    backuprootsuffix=`grep "ds.rootsuffix.key=" $BACKUPINF | sed -e "s/ds.rootsuffix.key=//"`
	    if [ "$rootsuffix" = "$backuprootsuffix" ]; then 
	      
	      if [ $VERBOSE -eq 1 ]; then
	        $ds_location/ldif2db -s "$rootsuffix" -i "$WORKDSDIR/$LDIF_FILE"
			return $?
	      else
	        $ds_location/ldif2db -s "$rootsuffix" -i "$WORKDSDIR/$LDIF_FILE" > /dev/null 2>&1
			return $?
	      fi
	      
	    else
	      $ECHO "`$gettext 'Rootsuffix differs: will not restore DS'`"
		  return 1
	    fi
	  else
	    $ECHO "`$gettext 'Remote Directory Server: will not restore DS'`"
		return 2
	  fi
	  }

        # code for getting amadmin password.
        get_amadmin_password()
         {
          faced_passwd_error="no"
          while [ 1 ]
          do
            print "\a`$gettext 'enter amadmin password..'`"
            stty -echo
            read amadmin_password
            stty echo
            amadmin_password=`$ECHO "$amadmin_password" | sed -e 's/ *$//'`
            if [ "$amadmin_password" = "" ]
            then
                $ECHO "\a `$gettext 'You must enter a password!'`"
                continue
            else
                break
            fi
          done
          
          $LDAPSEARCH -h $ldaphost -p $ldapport -D "$amadmin" -w "$amadmin_password" -b "$rootsuffix" entrydn=ou=services,* 1>search_out 2>search_err
          if [ $? != 0 ]; then
            faced_passwd_error="yes"            
            grep -i "Invalid Credentials" search_err
            if [ $? = 0 ]; then
              print "\a`$gettext 'amadmin password wrong..Reenter amadmin password...'`"
              stty -echo
              read amadmin_password
              stty echo
              amadmin_password=`$ECHO "$amadmin_password" | sed -e 's/ *$//'`
            fi
          fi
          if [ "$faced_passwd_error" = "yes" ]; then
            $LDAPSEARCH -h $ldaphost -p $ldapport -D "$amadmin" -w "$amadmin_password" -b "$rootsuffix" entrydn="ou=services,*"  1>search_out 2>search_err
            if [ $? != 0 ]; then
              return 1
            fi
          fi
          return 0
         }



########################################

check_root_user

check_for_running_am
FILENAME=""
BACKUPDIR="$PACKAGEDIR/backup"
VERBOSE=0
CONFIG=0
DEBUG=0
LOG=0
CERT=0
DS=0
TRY_COUNT=0
SUCCESS_COUNT=0
ARGCOUNT=$#

while [ $# -ne 0 ]
do
  case "$1" in
	'-v')
		VERBOSE=1
		;;
	'--verbose')
		VERBOSE=1
		;;
	'-z')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		FILENAME="$2"
		FILETYPE="gzip"
		shift
		;;
	'--gzip')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		FILENAME="$2"
		FILETYPE="gzip"
		shift
		;;
	'-t')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		FILENAME="$2"
		FILETYPE="tar"
		shift
		;;
	'--tar')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		FILENAME="$2"
		FILETYPE="tar"
		shift
		;;
	'-h')
		display_help
		exit 0
		;;
	'--help')
		display_help
		exit 0
		;;
	'-n')
		$ECHO ""
		$ECHO "`$gettext \"Sun Java System Identity Server version 2004Q2\"`"
		$ECHO ""
		exit 0
		;;
	'--version')
		$ECHO ""
		$ECHO "`$gettext \"Sun Java System Identity Server version 2004Q2\"`"
		$ECHO ""
		exit 0
		;;
	*)
		display_usage
		exit 1
		;;
  esac
shift
done

if [ $ARGCOUNT -lt 2 ]; then
  display_usage
  exit 1
fi

########################################

$ECHO "`$gettext 'Inspecting system .. verifying input file.......'`"

VALID_FILE=0
check_for_invalid_chars $FILENAME

if [ $? = 0 ]; then
   DIRNAME=`dirname $FILENAME`

   if [ "$DIRNAME" = "." ]; then
       FILENAME=$BACKUPDIR/$FILENAME
   fi
   
   if [ -f "$FILENAME" ]; then
       VALID_FILE=1
   else
       $ECHO "`$gettext 'No such file : exiting !!'`"
       exit 1
   fi
else
   $ECHO "`$gettext 'Invalid characters entered for backup-name: exiting !!'`"
   exit 1
fi

# directory now exists check for validity

DIRNAME=`dirname $FILENAME`

if [ "$FILETYPE" = "gzip" ]; then
  WORKFILE=temp.tar.gz
  cp -rp $FILENAME $WORKFILE

  /usr/bin/gunzip $WORKFILE > /dev/null 2>&1
  num=$?

  if [ -f "$WORKFILE" ]; then
	rm -rf $WORKFILE
  fi
  if [ $num -eq 0 ]; then
  	WORKFILE=`$ECHO $WORKFILE | sed -e "s/.gz//"`
  elif [ $num -eq 1 ]; then
	do_cleanup
	$ECHO "`$gettext 'File corrupted: exiting !!'`"
	exit 1
  elif [ $num -eq 2 ]; then
	do_cleanup
	$ECHO "`$gettext 'Unknown file format: exiting !!'`"
	exit 2
  fi
elif [ "$FILETYPE" = "tar" ]; then
  WORKFILE=temp.tar
  cp -rp $FILENAME $WORKFILE
fi

# now do tar xf, WORKFILE is a tar file

/usr/bin/tar -xf $WORKFILE > /dev/null 2>&1
if [ $? -eq 0 ]; then
  FILENAME=`basename $FILENAME`
  PWD=`pwd`
  FILENAME=$PWD/$FILENAME
  rm -rf $WORKFILE
  if [ "$FILETYPE" = "gzip" ]; then
	WORKDIR=`$ECHO $FILENAME | sed -e "s/.tar.gz//"`
  elif [ "$FILETYPE" = "tar" ]; then
	WORKDIR=`$ECHO $FILENAME | sed -e "s/.tar//"`
  fi
  if [ -f "$WORKDIR/backup.inf" ]; then
    $ECHO "`$gettext 'Input file is valid.......'`"
  else 
	do_cleanup
	$ECHO "`$gettext 'Identity Server Backup archive is not valid: exiting !!'`"
    exit 1
  fi
else
  do_cleanup
  $ECHO "`$gettext 'File corrupted or Unknown file format: exiting !!'`"
  exit 1
fi

# input file is valid now stop Identity Server
if [ "$running_am" = "yes" ]; then
yesno "`$gettext 'Identity Server must be stopped before restoring, stop ??'`" "`$gettext 'n'`"
if [ "$ans" = "`$gettext 'y'`" ]; then
  $ECHO "`$gettext 'Stopping Identity Server.....'`"
  if [ $VERBOSE -eq 1 ]; then
    /etc/init.d/amserver stopall
  else
    /etc/init.d/amserver stopall > /dev/null 2>&1
  fi
  $ECHO "`$gettext 'Identity Server stopped.....'`"
elif [ "$ans" = "`$gettext 'n'`" ]; then
  do_cleanup
  $ECHO "`$gettext 'Can not restore : exiting !!'`"
  exit 1
fi
fi

# now parse backup.inf and restore
$ECHO "`$gettext 'Restore in progress.......'`"
WORKDIR=`(cd "$WORKDIR"; pwd)`
BACKUPINF=$WORKDIR/backup.inf

CONFIG=`grep "config.backup.key=" $BACKUPINF | sed -e "s/config.backup.key=//"`
DEBUG=`grep "debug.backup.key=" $BACKUPINF | sed -e "s/debug.backup.key=//"`
LOG=`grep "log.backup.key=" $BACKUPINF | sed -e "s/log.backup.key=//"`
CERT=`grep "cert.backup.key=" $BACKUPINF | sed -e "s/cert.backup.key=//"`
DS=`grep "ds.backup.key=" $BACKUPINF | sed -e "s/ds.backup.key=//"`
ds_old_location=`grep "ds.location.key=" $BACKUPINF | sed -e "s/ds.location.key=//"`
cert_location=`grep "cert.location.key=" $BACKUPINF | sed -e "s/cert.location.key=//"`

if [ "$ds_old_location" != "" ] ; then
  if [ "$ds_old_location" != "$" ] ; then
    check_for_ds
    check_for_running_ds
  fi
fi

if [ "$ds" = "yes" ]; then
  if [ "$running_ds" = "yes" ]; then
	yesno "`$gettext 'Directory Server must be stopped before restoring, stop ??'`" "`$gettext 'n'`"
	if [ "$ans" = "`$gettext 'y'`" ]; then
      $ECHO "`$gettext 'Stopping Directory Server.....'`"
	  stop_ds
      $ECHO "`$gettext 'done.....'`"
	elif [ "$ans" = "`$gettext 'n'`" ]; then
  	  do_cleanup
  	  $ECHO "`$gettext 'Can not restore : exiting !!'`"
  	  exit 1
	fi	
  fi
fi

# restore Directory Server
if [ "$DS" = "1" ]; then
  if [ "$ds" = "yes" ]; then
	TRY_COUNT=`expr $TRY_COUNT + 1`
	do_restore_ds
	if [ $? -eq 0 ]; then
	  $ECHO "`$gettext 'Restored Directory Server...'`"
	  SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
	else
	  $ECHO "`$gettext 'Directory Server Restore failed...'`"
	fi
  fi
fi

# restore config
if [ "$CONFIG" = "1" ]; then
  TRY_COUNT=`expr $TRY_COUNT + 1`
  do_restore_config
  if [ $? -eq 0 ]; then
	$ECHO "`$gettext 'Restored Configuration...'`"
	SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
  else
	$ECHO "`$gettext 'Configuration Restore failed...'`"
  fi
fi

# restore debug
if [ "$DEBUG" = "1" ]; then
  TRY_COUNT=`expr $TRY_COUNT + 1`
  do_restore_debug
  if [ $? -eq 0 ]; then
	$ECHO "`$gettext 'Restored Debug files...'`"
	SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
  else
	$ECHO "`$gettext 'Debug Restore failed...'`"
  fi
fi

# restore log
if [ "$LOG" = "1" ]; then
  TRY_COUNT=`expr $TRY_COUNT + 1`
  do_restore_log
  if [ $? -eq 0 ]; then
	$ECHO "`$gettext 'Restored Log files...'`"
	SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
  else
	$ECHO "`$gettext 'Log Restore failed...'`"
  fi
fi

# restore cert
if [ "$CERT" = "1" ]; then
  TRY_COUNT=`expr $TRY_COUNT + 1`
  do_restore_cert
  if [ $? -eq 0 ]; then
	$ECHO "`$gettext 'Restored Cert db...'`"
	SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
  else
	$ECHO "`$gettext 'Cert db Restore failed...'`"
  fi
fi


do_cleanup

if [ $TRY_COUNT -eq $SUCCESS_COUNT ]; then 
  $ECHO "`$gettext 'Identity Server restore success:: restart the container and directory server manually..'`"
elif [ $SUCCESS_COUNT -eq 0 ]; then
  $ECHO "`$gettext 'Identity Server restore completely failed..'`"
  exit 1
else
  $ECHO "`$gettext 'Error encountered during Identity Server restore..'`"
  exit 2
fi
  
exit 0

########################################################
