#!/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
  LDAPSEARCH=$PACKAGEDIR/bin/ldapsearch
  LDAP_LIBRARY_PATH=$PACKAGEDIR/ldaplib/ldapsdk

  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 instance directory...enter $ for remote installation'`"
                read ds_location
                if [ "$ds_location" = "$" ]; then
	          $ECHO "ds.location.key=$ds_location" >> $INF_FILE
                  return 1
                fi
	        check_for_invalid_chars $ds_location 
	        if [[ $? = 0 && -d $ds_location && -f $ds_location/config/dse.ldif ]]; then
	          valid_ds_location="yes"
	          $ECHO "ds.location.key=$ds_location" >> $INF_FILE
                  return 0
                else
		  print "\a`$gettext 'Invalid response!'`"
                fi
            done
 
          }
          
	get_cert_location() 
	  {
	    valid_cert_location="no"
	    obtained_cert_location="yes"
            while [ "$valid_cert_location" = "no" ]; do
	        print "\a`$gettext 'Enter certificate directory...'`"
                read cert_location
	        check_for_invalid_chars $cert_location 
	        if [[ $? = 0 && -d $cert_location ]]; then
	          valid_cert_location="yes"
	          $ECHO "cert.location.key=$cert_location" >> $INF_FILE
                  return 0
                else
		  print "\a`$gettext 'Invalid response!'`"
                fi
            done
 
          }
          
        # 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
 	  }

	# get debug location
	get_debug_location()
	  {
	  DEBUGLOCATION=`grep "com.iplanet.services.debug.directory=" $PLATFORMCONF | sed -e "s/com.iplanet.services.debug.directory=//"`
	  
	  if [ "$DEBUGLOCATION" = "" ]; then
		return 1
	  fi

	  return 0
	  }

	# get log location
	get_log_location()
	  {
	    valid_log_location="no"
            while [ "$valid_log_location" = "no" ]; do
	        print "\a`$gettext 'Enter log directory...enter $ for remote logging service..'`"
                read LOGLOCATION
                if [ "$LOGLOCATION" = "$" ]; then
                  return 1
                fi
	        check_for_invalid_chars $LOGLOCATION
	        if [[ $? = 0 && -d $LOGLOCATION ]]; then
	          valid_log_location="yes"
                  return 0
                else
		  print "\a`$gettext 'Invalid response!'`"
                fi
            done
	  }
	  	
	# display help
	display_help()
	  {
	  display_usage
	  $ECHO 
	  $ECHO "`$gettext 'Where:'`"
  	  $ECHO "`$gettext '    backup-name		name of the backup (default is ambak)'`"
  	  $ECHO "`$gettext '    location		location of the backup(default is <install-dir>/backup)'`"
	  $ECHO 
	  $ECHO "`$gettext 'Options:'`"
  	  $ECHO "`$gettext '    -v or --verbose 	run in verbose mode'`"
  	  $ECHO "`$gettext '    -c or --config	take backup of only configuration files'`"
  	  $ECHO "`$gettext '    -b or --debug	take backup of only debug files`"
  	  $ECHO "`$gettext '    -g or --log		take backup of only log files`"
  	  $ECHO "`$gettext '    -t or --cert	take backup of only cert db`"
  	  $ECHO "`$gettext '    -d or --ds		take backup of only directory server`"
  	  $ECHO "`$gettext '    -a or --all		take complete backup of Identity Server`"	
	  }

	# display usage
	display_usage()
	  {
	  $ECHO "`$gettext 'Usage: ' `"
	  $ECHO "`$gettext '   ' `$0 [ -v | --verbose ] [ -k | --backup <backup-name> ]"
	  $ECHO "`$gettext '	[ -l | --location <location> ] [[-c | --config] | [-b | --debug]'`"
	  $ECHO "`$gettext '	| [-g | --log] | [-t | --cert] | [-d | --ds] | [-a | --all]]*'`"
  	  $ECHO "`$gettext '   ' `$0 -h | --help"
  	  $ECHO "`$gettext '   ' `$0 -n | --version"
	  }
	
	# copy and verbose
	copy_and_verbose()
	  {
	  SOURCE=$1
	  DESTINATION=$2

	  if [ $VERBOSE -eq 1 ]; then 
	    $ECHO "`$gettext 'Backing up : '` $SOURCE"
	  fi
	  
	  cp -rp $SOURCE $DESTINATION
	  if [ $? -ne 0 ]; then
        COPY_ERROR=1
	    $ECHO "`$gettext 'Backup of : '` $SOURCE `$gettext ' Failed'`" 
      else
	  	$ECHO "Backup from:$SOURCE to:$DESTINATION" >> $INF_FILE
	  	if [ $VERBOSE -eq 1 ]; then 
	      $ECHO "`$gettext 'Backup of : '` $SOURCE `$gettext ' done'`" 
	  	fi
	  fi
	  }
	
	# backup config
	do_backup_config()
	  {
	  $ECHO "`$gettext 'Configuration backup in progress...'`"
          COPY_ERROR=0

	  # create directory structure first
	  BACKUPCONFIGDIR=$BACKUPDIR/config
	  mkdir -p $BACKUPCONFIGDIR

	  mkdir -p $BACKUPCONFIGDIR/IS_PRODNAME
	  mkdir -p $BACKUPCONFIGDIR/IS_PRODNAME/lib
	  mkdir -p $BACKUPCONFIGDIR/IS_PRODNAME/bin
          
          if [ $WEBCONTAINER = "WS6" ]; then
            mkdir -p $BACKUPCONFIGDIR/ws
          fi
          
	  mkdir -p $BACKUPCONFIGDIR/etc/rc3.d

	  # start backup	  
	  $ECHO "configuration backup:" >> $INF_FILE
	  
	  copy_and_verbose IS_INSTALL_ETCDIR/IS_PRODNAME/config $BACKUPCONFIGDIR/IS_PRODNAME/.
	  copy_and_verbose $PACKAGEDIR/locale $BACKUPCONFIGDIR/IS_PRODNAME/.	  
          
	  for props in `ls $PACKAGEDIR/lib/*.properties`
	  do
	    copy_and_verbose $props $BACKUPCONFIGDIR/IS_PRODNAME/lib/.
	  done

	  for instance in `ls $PACKAGEDIR/bin | grep amserver.`
	  do
		if [ "$instance" != "amserver.instance_template" ]; then
			copy_and_verbose $PACKAGEDIR/bin/$instance $BACKUPCONFIGDIR/IS_PRODNAME/bin/.
		fi
	  done
          if [ $WEBCONTAINER = "IBM_WEBSPHERE" ]; then
               # take backup of setupCmdLine.sh
	       copy_and_verbose $WEBSPHERE_DIR/bin/setupCmdLine.sh $BACKUPCONFIGDIR/.
	       # take backup of admin.config
	       copy_and_verbose $WEBSPHERE_DIR/bin/admin.config $BACKUPCONFIGDIR/.
	       # take backup of plugin-cfg.xml
	       copy_and_verbose $WEBSPHERE_DIR/config/plugin-cfg.xml $BACKUPCONFIGDIR/.
	       # take backup of applications
	       copy_and_verbose $WEBSPHERE_DIR/installedApps $BACKUPCONFIGDIR/.
	       
          else if [ $WEBCONTAINER = "BEA_WEBLOGIC" ]; then
               # take backup of startWebLogic.sh
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/startWebLogic.sh $BACKUPCONFIGDIR/.
               # take backup of startManagedWebLogic.sh
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/startManagedWebLogic.sh $BACKUPCONFIGDIR/.
               # take backup of .java.login.config
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.java.login.config $BACKUPCONFIGDIR/.
               # take backup of config.xml
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/config.xml $BACKUPCONFIGDIR/.
               
               # take the backup of applications
               mkdir -p $BACKUPCONFIGDIR/IS_PRODNAME
               copy_and_verbose $PACKAGEDIR/web-apps $BACKUPCONFIGDIR/IS_PRODNAME/.
	
               # take the backup of WAR files deployed on WebLogic
               mkdir -p $BACKUPCONFIGDIR/.wlstaging
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/amcommon.war $BACKUPCONFIGDIR/.wlstaging/.
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/amconsole.war $BACKUPCONFIGDIR/.wlstaging/.
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/ampassword.war $BACKUPCONFIGDIR/.wlstaging/.
               copy_and_verbose $WEBLOGIC_DIR/config/$WEBLOGIC_DOMAIN/.wlstaging/amserver.war $BACKUPCONFIGDIR/.wlstaging/.

          else if [ $WEBCONTAINER = "AS7" ]; then
               # take backup of server.xml
               copy_and_verbose $S1ASINSTANCEDIR/config/server.xml $BACKUPCONFIGDIR/.
               # take backup of server.policy
               copy_and_verbose $S1ASINSTANCEDIR/config/server.policy $BACKUPCONFIGDIR/.
               DEBUGLOCATION=`grep "com.iplanet.services.debug.directory=" $PLATFORMCONF | sed -e "s/com.iplanet.services.debug.directory=//"`
               # get the locations of amserver, amconsole, introduction. These include location=
	       AMSERVERLOCATION=`grep "amserver" $S1ASINSTANCEDIR/config/server.xml | awk ' { 
									    for ( i=0;;i++) {
										if ( $i ~ /^location=/ ) {
										    print $i
										    break
										}
									    }					
								    } '` 
               AMCONSOLELOCATION=`grep "amconsole" $S1ASINSTANCEDIR/config/server.xml | awk ' { 
									    for ( i=0;;i++) {
										if ( $i ~ /^location=/ ) {
										    print $i
										    break
										}
									    }					
								    } '` 
               INTRODUCTIONLOCATION=`grep "amcommon" $S1ASINSTANCEDIR/config/server.xml | awk ' { 
									    for ( i=0;;i++) {
										if ( $i ~ /^location=/ ) {
										    print $i
										    break
										}
									    }					
								    } '`     
               PASSWDLOCATION=`grep "ampassword" $S1ASINSTANCEDIR/config/server.xml | awk ' { 
									    for ( i=0;;i++) {
										if ( $i ~ /^location=/ ) {
										    print $i
										    break
										}
									    }					
								    } '`     
               #remove the location=" and trailing "
               AMSERVER=`echo $AMSERVERLOCATION | sed -e "s/location=//"`
               AMSERVER=`echo $AMSERVER | sed -e "s/\"//g"`

               AMCONSOLE=`echo $AMCONSOLELOCATION | sed -e "s/location=//"`
               AMCONSOLE=`echo $AMCONSOLE | sed -e "s/\"//g"`
               
               INTRODUCTION=`echo $INTRODUCTIONLOCATION | sed -e "s/location=//"`
               INTRODUCTION=`echo $INTRODUCTION | sed -e "s/\"//g"`
               
               PASSWD=`echo $PASSWDLOCATION | sed -e "s/location=//"`
               PASSWD=`echo $PASSWD | sed -e "s/\"//g"`
               
               mkdir -p $BACKUPCONFIGDIR/applications/j2ee-modules               
               copy_and_verbose $AMSERVER $BACKUPCONFIGDIR/applications/j2ee-modules/.
               copy_and_verbose $AMCONSOLE $BACKUPCONFIGDIR/applications/j2ee-modules/.
               copy_and_verbose $INTRODUCTION $BACKUPCONFIGDIR/applications/j2ee-modules/.
               copy_and_verbose $PASSWD $BACKUPCONFIGDIR/applications/j2ee-modules/.
               
          else if [ $WEBCONTAINER = "WS6" ]; then
              copy_and_verbose $WS_LOCATION/httpacl $BACKUPCONFIGDIR/ws/.
              for instance in `ls $WS_LOCATION | grep https-`
              do
                    if [ "$instance" != "https-admserv" ]; then
                            copy_and_verbose $WS_LOCATION/$instance $BACKUPCONFIGDIR/ws/.
                    fi
              done

              for instance in `ls $WS_LOCATION | grep web-apps-`
              do
                    copy_and_verbose $WS_LOCATION/$instance $BACKUPCONFIGDIR/ws/.
              done

              copy_and_verbose $PACKAGEDIR/web-src $BACKUPCONFIGDIR/IS_PRODNAME/.
              
            fi          
           fi
          fi
	 fi
         # copy the K & S scripts, they will be considered as files though they are links
         # at the time of restore the links will be created instead of files
         if [ -f "/etc/rc1.d/K03amserver" ]; then
            mkdir -p $BACKUPCONFIGDIR/etc/rc1.d
            copy_and_verbose /etc/rc1.d/K03amserver $BACKUPCONFIGDIR/etc/rc1.d/.
         fi
         if [ -f "/etc/rc2.d/K03amserver" ]; then        
            mkdir -p $BACKUPCONFIGDIR/etc/rc2.d
            copy_and_verbose /etc/rc2.d/K03amserver $BACKUPCONFIGDIR/etc/rc2.d/.
         fi
         if [ -f "/etc/rc3.d/S86amserver" ]; then
            mkdir -p $BACKUPCONFIGDIR/etc/rc3.d
            copy_and_verbose /etc/rc3.d/S86amserver $BACKUPCONFIGDIR/etc/rc3.d/.
         fi

	  get_ds_location 
	  if [ $? = 0 ]; then
	    # if taking remote ds also put this mkdir above with all other mkdir's
	    mkdir -p $BACKUPCONFIGDIR/ldap-host/config
	    copy_and_verbose $ds_location/config/schema $BACKUPCONFIGDIR/ldap-host/config/.
	    copy_and_verbose $ds_location/config/dse.ldif $BACKUPCONFIGDIR/ldap-host/config/.
	  else
	    $ECHO "`$gettext 'Remote Directory Server: will not backup DS configuration files'`"
	  fi
          return $COPY_ERROR
	  }
	
        # backup of service config
        do_backup_serviceconfig()
          {
	  SSL_MODE=`grep "com.iplanet.am.directory.ssl.enabled=" $PLATFORMCONF | sed -e "s/com.iplanet.am.directory.ssl.enabled=//"`
          `$ECHO $SSL_MODE | grep -i "true"`
          if [ $? = 0 ]; then
            print "\a`$gettext 'Directory Server running in ssl mode..Use DS backup tools for service configuration backup...'`"
            return 1
          fi
          export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$LDAP_LIBRARY_PATH
          print "\a`$gettext 'Service Configuration backup in progress...'`"
	  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=//"`
          faced__connection_error="no"
	  amadmin=`grep "com.sun.identity.authentication.super.user=" $PLATFORMCONF | sed -e "s/com.sun.identity.authentication.super.user=//"`
          $LDAPSEARCH -h $ldaphost -p $ldapport -D "$amadmin" -w "$amadmin_password" -b "$rootsuffix" entrydn=ou=services,*  1>search_out 2>search_err
          if [ $? != 0 ]; then
            cat search_err
            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 backup not done...'`"
              rm search_err search_out
              return 1
            fi
          else 
            get_amadmin_password
            if [ $? = 1 ]; then
              print "\a`$gettext 'service configuration backup not done...'`"
              rm search_err search_out
              return 1
            fi
          fi          
          echo "`grep -i "$rootsuffix" search_out`" > search_dns
          cat search_dns | awk ' {
                               if ( $0 ~ /^dn:/ ) {
                                   if ( DN != "" ) {
                                     print DN
                                     DN=""
                                  }
                                  DN=$0  
                              }
                              else {                            
                                  if ( $0 ~ /^ / ) {
                                    len = length($0)
                                    required = substr($0,2,len-1)
                                    DN = DN required
                                 }
                              }
                            }
                            END {
                                if ( DN != "") {
                                   print DN
                                }                           
                          }' > extract_dns
          echo "`sed -e 's/dn: //g' extract_dns`" > stripoff_dns          
          cat stripoff_dns | /usr/bin/nawk -v LDAPSEARCH=$LDAPSEARCH -v ldaphost=$ldaphost -v ldapport=$ldapport -v amadmin="$amadmin" -v amadmin_password="$amadmin_password" -v BACKUPCONFIGDIR=$BACKUPCONFIGDIR -v ECHO=$ECHO '{            
            buf=sprintf("%s -h %s -p %s -D \"%s\" -w \"%s\" -b \"%s\" objectclass=\"*\" >> %s/updated_services.ldif \n", LDAPSEARCH , ldaphost , ldapport , amadmin , amadmin_password , $0 , BACKUPCONFIGDIR);            
            system(buf);            
            buf=sprintf("%s \\n >> %s/updated_services.ldif", ECHO , BACKUPCONFIGDIR);
            system(buf);            
          }'  
          
          rm search_err search_out search_dns extract_dns stripoff_dns
          return $?
	  }
	
	# backup debug
	do_backup_debug()
	  {
	  if [ ! -d "$DEBUGLOCATION" ]; then
		$ECHO "`$gettext 'Debug directory does not exist .. will not backup debug files..'`"
		return 2
	  fi

	  $ECHO "`$gettext 'Debug backup in progress...'`"
	  COPY_ERROR=0

	  BACKUPDEBUGDIR=$BACKUPDIR/debug

	  $ECHO "debug backup:" >> $INF_FILE
	  $ECHO "debug.location.key=$DEBUGLOCATION" >> $INF_FILE

	  copy_and_verbose $DEBUGLOCATION $BACKUPDEBUGDIR

          return $COPY_ERROR
	  }

        # backup log
	do_backup_log()
          {
          $ECHO "`$gettext 'Log backup in progress...'`"
          COPY_ERROR=0

          # create directory structure first
          BACKUPLOGDIR=$BACKUPDIR/log
	  mkdir -p $BACKUPLOGDIR

          $ECHO "log backup:" >> $INF_FILE
          $ECHO "log.location.key=$LOGLOCATION" >> $INF_FILE

          copy_and_verbose $LOGLOCATION $BACKUPLOGDIR/logs

          copy_and_verbose /var/sadm/install/logs $BACKUPLOGDIR/install 

          return $COPY_ERROR
          }

	# backup cert
	do_backup_cert()
	  {
          get_cert_location
	  $ECHO "`$gettext 'Cert db backup in progress...'`"
	  COPY_ERROR=0
	  
	  # create directory structure first
	  BACKUPCERTDIR=$BACKUPDIR/cert
	  mkdir -p $BACKUPCERTDIR

	  mkdir -p $BACKUPCERTDIR/ds
	  mkdir -p $BACKUPCERTDIR/cert
	  	  
	  # start backup	  
	  $ECHO "cert db backup:" >> $INF_FILE
	 for certs in `ls $cert_location`
          do
            copy_and_verbose $cert_location/$certs $BACKUPCERTDIR/cert/. 
          done
 
	  if [ "$valid_ds_location" = "yes" ]; then
	    copy_and_verbose $ds_location/../alias $BACKUPCERTDIR/ds/.
          elif [ "$obtained_ds_location" = "yes" ] ; then
	      $ECHO "`$gettext 'Remote Directory Server: will not backup DS cert'`"
          else
            get_ds_location
            if [ $? = 0 ] ; then 
	      copy_and_verbose $ds_location/../alias $BACKUPCERTDIR/ds/.
            else
	      $ECHO "`$gettext 'Remote Directory Server: will not backup DS cert'`"
            fi
	  fi

      return $COPY_ERROR	  
	  }
		
	# backup ds
	do_backup_ds()
	  {
	  $ECHO "`$gettext 'Directory server backup in progress...'`"
	  # create directory structure first
	  BACKUPDSDIR=$BACKUPDIR/ds
	  mkdir -m 777 -p $BACKUPDSDIR
	
          $ECHO "ds backup:" >> $INF_FILE
	  rootsuffix=`grep "com.iplanet.am.rootsuffix=" $PLATFORMCONF | sed -e "s/com.iplanet.am.rootsuffix=//"`
	  $ECHO "ds.rootsuffix.key=$rootsuffix" >> $INF_FILE
	  if [ -f $ds_location/db2ldif ] ; then

	    if [ $VERBOSE -eq 1 ]; then
	      $ds_location/db2ldif -s "$rootsuffix" -a "$BACKUPDSDIR/$FILENAME.ldif" 2>&1 
              return $?
	    else
	      $ds_location/db2ldif -s "$rootsuffix" -a "$BACKUPDSDIR/$FILENAME.ldif" > /dev/null 2>&1
              return $?
	    fi
          else
             return 1
          fi
	  }

	# tar all and delete source
	do_tar()
	  {
	  # everything done :: now tar it and delete the source
      if [ $SUCCESS_COUNT -eq 0 ]; then
        /usr/bin/rm -rf $BACKUPDIR
        $ECHO "`$gettext 'Backup failed completely...'`"
        exit 1
      else            
	  cd $BACKUPDIR/../
	  /usr/bin/tar -cf $BACKUPDIR.tar $FILENAME
        /usr/bin/rm -rf $BACKUPDIR
        /usr/bin/gzip $BACKUPDIR.tar
        chmod 700 $BACKUPDIR.tar.gz
        $ECHO "`$gettext 'Backup finished, file is : '` $BACKUPDIR.tar.gz"
      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

FILENAME="ambak"
TIMESTAMP=`date +_%Y_%m_%d_%H%M%S`
BACKUPDIR="$PACKAGEDIR/backup/"

if [[ $# -eq 0 || ($# -eq 1 && ("$1" = "--verbose" || "$1" = "-v")) ]]; then
  $ECHO "`$gettext 'Starting backup with default options...'`"
  $ECHO "`$gettext 'Complete Identity Server backup..'`"
  $ECHO "`$gettext 'Backup Directory= '` $BACKUPDIR"
  $ECHO "`$gettext 'Backup file name= '` $FILENAME$TIMESTAMP.tar.gz"
  yesno "`$gettext 'Do you want to continue..?'`" "`$gettext 'y'`"
  if [ "$ans" = "`$gettext 'y'`" ]; then
    PROCEED=1
  elif [ "$ans" = "`$gettext 'n'`" ]; then
    display_help
    exit 1
  fi
fi  

VERBOSE=0
CONFIG=0
DEBUG=0
LOG=0
CERT=0
DS=0
ALL=1
SUCCESS_COUNT=0

while [ $# -ne 0 ]
do
  case "$1" in
	'-v')
		VERBOSE=1
		;;
	'--verbose')
		VERBOSE=1
		;;
	'-k')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		FILENAME="$2"
		shift
		;;
	'--backup')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		FILENAME="$2"
		shift
		;;
	'-l')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		BACKUPDIR="$2"
		shift
		;;
	'--location')
		if [ "$2" = "" ]; then
		  display_usage
		  exit 1
		fi
		
		checknext=`$ECHO $2 | cut -d - -f1`
		if [ "$checknext" = "" ]; then 
		  display_usage
		  exit 1
		fi
		BACKUPDIR="$2"
		shift
		;;
	'-c')
		CONFIG=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;	
	'--config')
		CONFIG=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;
	'-b')
		DEBUG=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;	
	'--debug')
		DEBUG=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;
	'-g')
		LOG=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;	
	'--log')
		LOG=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;
	'-t')
		CERT=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;	
	'--cert')
		CERT=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;	
	'-d')
		DS=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;	
	'--ds')
		DS=1
		if [ $ALL -eq 1 ]; then
		  ALL=0
		fi
		;;
	'-a')
		ALL=2
		;;	
	'--all')
		ALL=2
		;;
	'-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

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

check_for_invalid_chars $FILENAME

if [ $? != 0 ]; then
  $ECHO "`$gettext 'Invalid characters entered for backup-name : exiting !!'`"
  exit 1
fi

check_for_invalid_chars $BACKUPDIR

if [ $? = 0 ]; then
  if [ "$BACKUPDIR" != "/" ]; then 
   # Check for the trailing spaces
   BACKUPDIR=`$ECHO ${BACKUPDIR} | sed -e 's/\/$//'`
   if [ ! -d "$BACKUPDIR" ]; then
     yesno "\"$BACKUPDIR\" `$gettext ' does not exist, create?'`" "`$gettext 'y'`"
     if [ "$ans" = "`$gettext 'y'`" ]; then
       mkdir -m 700 -p "$BACKUPDIR"
       chown $SYS_OWNER:$SYS_GROUP $BACKUPDIR              

       if [ $? -ne 0 ]; then
        $ECHO "`$gettext 'Can not create directory : exiting !!'`"
        exit 2
       fi  
     elif [ "$ans" = "`$gettext 'n'`" ]; then
       $ECHO "`$gettext 'Can not perform backup : exiting !!'`"
       exit 1
     fi
   fi
  fi
else
   $ECHO "`$gettext 'Invalid characters entered for location : exiting !!'`"
   exit 1
fi

# Backup directory now exists :: create directory under that
if [ ! -w $BACKUPDIR ]; then
  $ECHO "`$gettext 'No write privilege on given location : exiting !!'`"
  exit 1
fi

FILENAME=$FILENAME$TIMESTAMP
BACKUPDIR=`(cd "$BACKUPDIR"; pwd)`
BACKUPDIR=`$ECHO ${BACKUPDIR} | sed -e 's/\/$//'`
BACKUPDIR=$BACKUPDIR/$FILENAME

$ECHO "`$gettext 'Backup in progress.......'`"

mkdir -m 700 -p $BACKUPDIR
chown $SYS_OWNER:$SYS_GROUP $BACKUPDIR

INF_FILE=$BACKUPDIR/backup.inf

if [ $ALL -ne 0 ]; then
  CONFIG=1
  DEBUG=1
  LOG=1
  CERT=1
  DS=1
fi

$ECHO "Backup information file !!DO NOT EDIT!!" > $INF_FILE


# now check  the options and do backup
# config backup
if [ $CONFIG -eq 1 ]; then
  do_backup_config
  if [ $? -eq 0 ]; then
    $ECHO "config.backup.key=1" >> $INF_FILE
    SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
    #backup the service config.
    if [ "$ds_location" = "$" ]; then
      do_serviceconfig="1"
    elif [ $DS -ne 1 ]; then
      do_serviceconfig="1"
    fi
    if [ "$do_serviceconfig" = "1" ]; then
      do_backup_serviceconfig
      if [ $? -eq 0 ]; then
        $ECHO "serviceconfiguration.backup.key=1" >> $INF_FILE
      fi
    fi
    $ECHO "`$gettext 'Configuration backup finished...'`"
  else
    $ECHO "config.backup.key=0" >> $INF_FILE
    if [ -e "$BACKUPCONFIGDIR" ]; then
      rm -rf $BACKUPCONFIGDIR
    fi
    $ECHO "`$gettext 'Configuration backup failed...'`"
  fi
else
  $ECHO "config.backup.key=0" >> $INF_FILE
fi

# debug backup
if [ $DEBUG -eq 1 ]; then
  get_debug_location
  if [ $? -ne 0 ]; then
    $ECHO "`$gettext 'Can not get debug location .. will not backup debug files..'`"
    $ECHO "debug.backup.key=0" >> $INF_FILE
  else
    do_backup_debug
    if [ $? -eq 0 ]; then
      $ECHO "debug.backup.key=1" >> $INF_FILE
      SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
      $ECHO "`$gettext 'Debug backup finished...'`"
    else
      $ECHO "debug.backup.key=0" >> $INF_FILE
      if [ -e "$BACKUPDEBUGDIR" ]; then
        rm -rf $BACKUPDEBUGDIR
      fi
      $ECHO "`$gettext 'Debug backup failed...'`"
    fi
  fi
else
  $ECHO "debug.backup.key=0" >> $INF_FILE    
fi

# log backup
if [ $LOG -eq 1 ]; then
    get_log_location
    if [ "$valid_log_location" = "no" ]; then
      $ECHO "`$gettext 'Can not get log location .. will not backup log files..'`"
      $ECHO "log.backup.key=0" >> $INF_FILE
    else
      do_backup_log
      if [ $? -eq 0 ]; then
        $ECHO "log.backup.key=1" >> $INF_FILE
        SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
        $ECHO "`$gettext 'Log backup finished...'`"
      else
        $ECHO "log.backup.key=0" >> $INF_FILE
        if [ -e "$BACKUPLOGDIR" ]; then
          rm -rf $BACKUPLOGDIR
        fi
        $ECHO "`$gettext 'Log backup failed...'`"
      fi
    fi
fi
# cert backup
if [ $CERT -eq 1 ]; then
  do_backup_cert
  if [ $? -eq 0 ]; then
    $ECHO "cert.backup.key=1" >> $INF_FILE
    SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
    $ECHO "`$gettext 'Cert db backup finished...'`"
  else
    $ECHO "cert.backup.key=0" >> $INF_FILE
    if [ -e "$BACKUPCERTDIR" ]; then
      rm -rf $BACKUPCERTDIR
    fi
    $ECHO "`$gettext 'Cert db backup failed...'`"
  fi
else
  $ECHO "cert.backup.key=0" >> $INF_FILE
fi

# ds backup
if [ $DS -eq 1 ]; then
  if [ "$obtained_ds_location" != "yes" ]; then
    get_ds_location
  fi
  if [ "$valid_ds_location" = "yes" ]; then
    do_backup_ds
    if [ $? -eq 0 ]; then
      $ECHO "ds.backup.key=1" >> $INF_FILE
      SUCCESS_COUNT=`expr $SUCCESS_COUNT + 1`
      $ECHO "`$gettext 'Directory server backup finished...'`"
    else
      $ECHO "ds.backup.key=0" >> $INF_FILE
      if [ -e "$BACKUPDSDIR" ]; then
        rm -rf $BACKUPDSDIR
      fi
      $ECHO "`$gettext 'Directory server backup failed...'`"
    fi
  else
    $ECHO "`$gettext 'Remote Directory Server: will not backup DS'`"
    $ECHO "ds.backup.key=0" >> $INF_FILE
  fi
else
  $ECHO "ds.backup.key=0" >> $INF_FILE
fi

do_tar

exit 0

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