#!/bin/sh 
#
# Copyright 06/28/04 Sun Microsystems, Inc. All Rights Reserved.
#
# pragma ident  "@(#)es-restore	1.44 04/06/28"
#

print_usage () {
    /bin/echo ""
    eval /bin/echo `/usr/bin/gettext 'Usage: $PROGNAME [-h] [-c] [-d dir]'`
    /usr/bin/gettext '     -h      : Prints this usage.\n'
    /usr/bin/gettext '     -d <dir>: Specify default backup directory path\n'
    /usr/bin/gettext '     -c      : Check backup only, do not restore\n'
    /bin/echo ""
}


# Internal utilities

print_failure_and_exit () {
    echolog ''
    echolog 'Restore operation failed. See $2 for details.' "$LOGFILE"

    # Just in case SunMC is still up
    stop_SunMC

    echolog ''
    exit $1
}

# meta_get
# Args:
#	$1	metafile
#	$2	key
#
# Outputs value to stdout; blank if no value.
meta_get () {
    /usr/bin/grep "^$2=" $1 | /usr/bin/cut -f2 -d=
}

exit_with_prm_instructions () {
    echolog 'You can restore your backup by doing the following steps:'
    echolog '  1. Uninstall PRM manually.'
    echolog '  2. Run es-restore again to restore your backup.'
    echolog '  3. Re-install PRM.'

    exit $1
}

check_backup_compatibility () {

# Check that there are no users in the backup that are not in the database.
# Check backup file against database.

start_db
for user_name in `/usr/bin/grep "_USER" $mfile | /usr/bin/cut -f2 -d=`; do
    ADDON_NAME=`/usr/bin/grep  "$user_name" $mfile | /usr/bin/cut -f1 -d_`
    db_checkUser $SYS_LOGIN $SYSPWD $user_name $LOGFILE
    if [ $? -ne 0 ] ; then
	echolog ''
	echolog 'The backup in $2 was made with the $3 addon installed.' "$BACKUPDIR" "$ADDON_NAME"
	echolog 'Your current Sun Management Center installation does not have the $2 addon setup.' "$ADDON_NAME"
	echolog 'These two configurations are not compatible. es-restore cannot correctly restore your backup data.'
	print_failure_and_exit 1
    fi
done

# Check that there are no users in the database that are not in the backup.
# Check database against backup.
sqlout=/tmp/sqlout.$$
/usr/bin/rm -f $sqlout

sql="select username from dba_users where username not in ('SYS','SYSTEM','OUTLN','DBSNMP','TRACESVR','SUNMC')"
db_runSqlSpool "$sql" "$sqlout" "SQL" "$SYS_LOGIN" "$SYSPWD" "$LOGFILE"

    if [ $? -eq 0 ] ; then
       for db_user in `/usr/bin/egrep '^[A-Z]*' $sqlout | grep -v SQL `; do
       usr_cnt=`/usr/bin/grep "_USER" $mfile | /usr/bin/cut -f2 -d= |/usr/bin/tr '[a-z]' '[A-Z]'| /usr/bin/egrep -i "^${db_user}$" `   
	if [ -z "$usr_cnt" ]; then
	   echolog ''
	   echolog 'The backup in $2 does not have the $3 user backed up.' "$BACKUPDIR" "$db_user"
	   echolog 'Your current Sun Management Center installation does have the $2 user setup.' "$db_user"
	   echolog 'These two configurations are not compatible. es-restore cannot correctly restore your backup data.'
	   /usr/bin/rm -f $sqlout
	   print_failure_and_exit 1
	fi
       done
    else 
	echologverbose 'Unable to retrieve list of users from the database.'
	/usr/bin/rm -f $sqlout
	print_failure_and_exit 1
    fi


}

read_metafile () {
    mfile=${BACKUPDIR}/$METAFILE

    if [ -f "$BACKUPDIR/sunmc.dmp" ] ; then
        #
        # Old backup format. Will handle using compatibility mode.
        #
        BACKUP_FORMAT=0
        echolog 'NOTE: the backup in $2 is made using an old version of es-backup.' "$BACKUPDIR"
        echolog 'Compatibility checks and validation will not be performed.'
        return

    elif [ -f "$mfile" ] ; then
        #
        # Identified a new backup
        #
        BACKUP_FORMAT=`meta_get $mfile BACKUP_FORMAT`
        if [ "$BACKUP_FORMAT" -lt 1 ] || [ "$BACKUP_FORMAT" -gt 4 ] ; then
            echolog 'The directory $2 contains a Sun Management Center backup format that is not supported by this version of es-restore.' "$BACKUPDIR"
            echolog 'You must restore this backup on a compatible version of Sun Management Center.'
            exit 1
        fi
        setup_backup_format $BACKUP_FORMAT

        BAK_SUNMC_VERSION=`meta_get $mfile SUNMC_VERSION`
        if [ "$BAK_SUNMC_VERSION" != "$SUNMC_VERSION" ] ; then
            echolog 'ERROR: The backup in $2 was created from a Sun Management Center $3 installation,' "$BACKUPDIR" "$BAK_SUNMC_VERSION"
            echolog 'Your current Sun Management Center version is $2.' "$SUNMC_VERSION"
            echolog 'es-restore cannot restore Sun Management Center $2 data into Sun Management Center $3.' "$BAK_SUNMC_VERSION" "$SUNMC_VERSION"
            exit 1
        fi

        BAK_ESCOM_BASEDIR=`meta_get $mfile ESCOM_BASEDIR`
        BAK_ESTBL_BASEDIR=`meta_get $mfile ESTBL_BASEDIR`

        BAK_HOSTNAME=`meta_get $mfile HOSTNAME`
        HOSTNAME=`/usr/bin/hostname`
        if [ "$BAK_HOSTNAME" != "$HOSTNAME" ] ; then
            echolog 'The backup in $2 was made from a Sun Management Center installation on a machine called $3.' "$BACKUPDIR" "$BAK_HOSTNAME"
            echolog 'Your current machine is $4.' "$HOSTNAME"
            echolog 'Restoring this backup into your current installation will cause some Sun Management Center server components to fail. Aborting.'
            exit 1
        fi

        COMPRESS_SCHEME=`meta_get $mfile COMPRESS_SCHEME`
        if [ "$COMPRESS_SCHEME" != "multi" ] ; then
            echolog 'Unsupported compression scheme $2 in backup.' "$COMPRESS_SCHEME"
            exit 1
        fi

        if [ "$BACKUP_FORMAT" -eq 3 ]; then
           HOT_TAG=`meta_get $mfile HOT_TAG`
           if [ -z "$HOT_TAG" ] ; then
               echolog 'Unable to identify requested hot backup. The tag is missing.'  
               exit 1
           fi
        fi

        COMPRESS_CMD=`meta_get $mfile COMPRESS_CMD`
        COMPRESS_EXT=`meta_get $mfile COMPRESS_EXT`
        ZCAT_CMD=`meta_get $mfile ZCAT_CMD`
        DB_CHUNKS=`meta_get $mfile DB_CHUNKS`
        if [ "$COMPRESS_CMD" =  "" ] || \
           [ "$COMPRESS_EXT" =  "" ] || \
           [ "$ZCAT_CMD"     =  "" ] || \
           [ "$DB_CHUNKS"   -lt 1  ] ; then
            echolog 'Information about the compression used in the backup appear to have been lost or corrupted.'
            echolog 'es-restore is unable to restore the backup data.'
            exit 1
        fi

    else
	echolog 'The directory $2 does not contain any recognizable Sun Management Center backup data.' "$BACKUPDIR"
	echolog "Ensure that all backup files are intact in that directory, and re-run es-restore."
	exit 1
    fi
}

# Checks an old 3.0 backup. Note that not much can be checked here; the old
# format does not have a meta file and so some information is missing.
check_old_backup () {

    #
    # This is all we can check for at the moment.
    #
    if [ -f $BACKUPDIR/cfg.tar.Z ] ; then
        echolog 'The file $2 is missing.' "$BACKUPDIR"
        print_failure_and_exit 1
    fi

    return 0
}

# get_split_sources $basename $num_chunks
#	Generates the list of expected filenames of the split backup, in the
#	correct fragment order, from $basename and $num_chunks. If $num_chunks
#	is 1, then $basename is returned unchanged. (This is to maintain
#	compatibility with es-backup and older versions of es-backup/restore.)
#
#	Also verifies that the files actually exist (so $basename should be
#	a full path or correct relative path for the current directory).
#
#	Returns list as $BAK_SRC_CHUNKS (space delimited).
get_split_sources () {
    basename=$1
    num_chunks=$2

    if [ "$num_chunks" -eq 1 ] ; then
        BAK_SRC_CHUNKS=$basename
    else
        get_split_names $basename. $num_chunks
        BAK_SRC_CHUNKS=$names
    fi

    # Verify that each listed file is actually there
    for src in $BAK_SRC_CHUNKS ; do
        if [ ! -f $src ] ; then
            echolog 'Part of the backup, the file $2, is missing.' "$src"
            return 1
        fi
    done

    return 0
}

# NOTE: need to load metafile and set env variables before calling this.
validate_backup () {

    # For old 3.0 es-backup compatibility.
    if [ "$BACKUP_FORMAT" -eq 0 ] ; then
        check_old_backup
        return $?
    fi

    #
    # Validate backup. Make sure we have a good, sane backup dir.
    #
    CFGBAKFILE=${BACKUPDIR}/${CFGFILE}.${COMPRESS_EXT}
    if [ ! -f "$CFGBAKFILE" ] ; then
        echolog 'The file $2 is missing.' "$CFGBAKFILE"
        print_failure_and_exit 1
    fi

    # Make sure cfg tarball is OK
    $ZCAT_CMD $CFGBAKFILE | /usr/bin/tar evfht - >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echolog 'Backup file $2 appears to be corrupt.' "$CFGBAKFILE"
        print_failure_and_exit 1
    fi

    #
    # Validate database backup file(s)
    #
    if [ "$BACKUP_FORMAT" -eq 1 ] ; then
        db_bak_file=${BACKUPDIR}/${DBBAKFILE}.${COMPRESS_EXT}

        get_split_sources $db_bak_file $DB_CHUNKS
        if [ $? -ne 0 ] ; then
            echolog 'The backup is incomplete. Cannot restore.' "$db_bak_file"
            print_failure_and_exit 1
        fi
    elif [ "$BACKUP_FORMAT" -eq 2 -o "$BACKUP_FORMAT" -eq 4 ] ; then
        db_bak_file=${BACKUPDIR}/${DUMPFILE}.${COMPRESS_EXT}

        get_split_sources $db_bak_file $DB_CHUNKS
        if [ $? -ne 0 ] ; then
            echolog 'The backup is incomplete. Cannot restore.' "$db_bak_file"
            print_failure_and_exit 1
        fi
    elif [ "$BACKUP_FORMAT" -eq 3 ] ; then

        # In order to be able to restore from online backup,
        # database must be in ARCHIVELOG mode.
        validate_archivelog_mode 
        if [ $? -ne 0 ]; then
           exit 1
        fi
    fi

    return 0
}

#
# Scan the database import log for errors
#
ora_scan_import_log ()
{
    file=$1
    error=`/usr/bin/egrep -n "ORA-|PLS-|SP2-|EXP-|IMP-" $file | /usr/bin/egrep -v "IMP-00015|ORA-01917|IMP-00017|IMP-00003" | /usr/bin/head -1| /usr/bin/cut -d: -f1`
    if [ "$error" -gt 0 ]; then
        numlines=`/usr/bin/wc -l $file | /usr/bin/awk '{print $1}'`
        offset=`/usr/bin/expr $numlines - $error`

        echolog "Oracle Error: Start..."
        /usr/bin/tail -${offset} $file >>$LOGFILE
        echolog "Oracle Error: End"
        return 1
    fi

    return 0
}


#
# Restore from cold backup (BACKUP_TYPE=1)
#
restore_cold () {

    cd $ESTBL_BASEDIR
    if [ $? -ne 0 ] ; then
        echolog 'Unable to access the directory $2' "$ESTBL_BASEDIR"
        return 1
    fi

    # Cold restore always overwrites existing Sun Management Center database.
    if [ -d "${ESTBL_BASEDIR}/$ORA_DATADIR" ] ; then
        clean_subdirs_smc ${ESTBL_BASEDIR}/$ORA_DATADIR
        if [ $? -ne 0 ] ; then
            echolog 'Unable to sym_clean up directory $2' "${ESTBL_BASEDIR}/$ORA_DATADIR"
            exit 1
        fi
    fi

    # Restore the database files
    /usr/bin/cat $BAK_SRC_CHUNKS | $ZCAT_CMD - | /usr/bin/tar xvphf - >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Failed to restore Sun Management Center data.'
        return 1
    fi

    # Restore the oradata directory permissions
    /usr/bin/chown -R $SMCORAU:$SMCORAG "${ESTBL_BASEDIR}/$ORA_DATADIR/oradata" >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Failed to restore Sun Management Center data directory permissions.'
    fi

    return 0
}

#
# Restore from online backup (BACKUP_TYPE=3)
#
restore_online () {

    # Initialize variables
    RESTORE_SCRIPT=${TMP_SMC_DB_LOGS}/rman-backup.rcv.$$

    # Database needs to be mounted, not open for this operation.
    # First, make sure that database is shutdown.
    shutdown_db noexit
     if [ $? -ne 0 ]; then
        echo ''
        echolog "It appears the database is corrupt. Proceeding with database recovery."
        echo ''
        kill_db
        # Assume the database was in the archivelog mode. We have no choice
    fi
    
    oratmp=/tmp/db-unset.$$
    /usr/bin/rm -f $oratmp
  
     # restore the control file using unix cp command.
    if [ ! -f "$BACKUPDIR/backup.ctl" ]; then
        echolog 'Unable to find the control file backup'
        exit 1
    else
    echologverbose "Restoring control file: $BACKUPDIR/backup.ctl"
        # It will be good to read the control files from initSunMC.ora
        # but since we hardcode it in db-common, it's ok even here.
        # in future this should be detected from pfile.
        /usr/bin/cp $BACKUPDIR/backup.ctl $ESTBL_BASEDIR/$ORA_DATADIR/oradata/SunMC/control01.ctl
        /usr/bin/cp $BACKUPDIR/backup.ctl $ESTBL_BASEDIR/$ORA_DATADIR/oradata/SunMC/control02.ctl
        /usr/bin/cp $BACKUPDIR/backup.ctl $ESTBL_BASEDIR/$ORA_DATADIR/oradata/SunMC/control03.ctl
        /usr/bin/chown smcorau $ESTBL_BASEDIR/$ORA_DATADIR/oradata/SunMC/*.ctl
        /usr/bin/chgrp smcorag $ESTBL_BASEDIR/$ORA_DATADIR/oradata/SunMC/*.ctl
    fi

    /usr/bin/su - $SMCORAU  -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
                        $ORACLE_HOME/bin/sqlplus -s /nolog<<EOF>$oratmp 2>/dev/null
connect / as sysdba;
set verify off;
set echo off;
set feedback off;
startup mount;
EOF"

    if [ $? -ne 0 ];then
        echolog 'Unable to mount the database'
        /usr/bin/rm -f $oratmp
        exit 1
    fi

    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ];then
        echolog 'Unable to mount the database'
        /usr/bin/rm -f $oratmp
        exit 1
    fi

    /usr/bin/rm -f $oratmp

    # Listener has to up and running in order for RMAN to connect to the database.
    /usr/bin/su - $SMCORAU -c ". $BASEDIR/sbin/es-common.sh; set_db_env;
                       lsnrctl <<EOF>$oratmp 2>/dev/null
start $SUNMCLISTENER
EOF"

    if [ $? -ne 0 ]; then
       echolog 'Could not start listener $2.' "$SUNMCLISTENER"
       /usr/bin/rm -f $oratmp
       exit 1
    fi

    db_checkErr $oratmp $LOGFILE

    if [ $? -ne 0 ]; then
       echolog 'Could not start listener $2.' "$SUNMCLISTENER"
       /usr/bin/rm -f $oratmp
       exit 1
    fi

BACKUP_DATE=`meta_get $mfile BACKUP_DATE`

SCN_FIRST=`meta_get $mfile SCN_FIRST`
SCN_NEXT=`meta_get $mfile SCN_NEXT`

if [ "$SCN_FIRST" -eq '0' ] ; then
restorestring="until SCN $SCN_NEXT"
else
restorestring="from SCN $SCN_FIRST until SCN $SCN_NEXT"
fi

# Generate  temporary backup script.
echo "run {
allocate channel ch1 type disk;
allocate channel ch2 type disk;
allocate channel ch3 type disk;
restore database from tag '${HOT_TAG}';
restore archivelog $restorestring;
recover database until SCN $SCN_NEXT;
alter database open resetlogs;
release channel ch1;
release channel ch2;
release channel ch3;
}" > ${RESTORE_SCRIPT}

    if [ $? -ne 0 ]; then
       echolog  'Failed to create temporary file $2' ${RESTORE_SCRIPT}
       /usr/bin/rm -f ${RESTORE_SCRIPT}
       /usr/bin/rm -f $oratmp
       exit 1
    fi

    # Fix the ownership to belong to database owner
    /usr/bin/chown $SMCORAU:$SMCORAG ${RESTORE_SCRIPT}
    if [ $? -ne 0 ]; then
       echolog "chown failed after changing the UID ansd GID of user - smcorau."
       /usr/bin/rm -f ${RESTORE_SCRIPT}
       /usr/bin/rm -f $oratmp
       exit 1
    fi
  
    echolog "Please wait while database is being restored..."

    # Use RMAN to restore the database.
    /usr/bin/su - $SMCORAU  -c ". $BASEDIR/sbin/es-common.sh; set_db_env; . $BASEDIR/lib/sbin/db-common.sh; set_db_password;
                        rman target ${SYS_LOGIN}/${SYSPWD}@${DED_SVR} nocatalog @${RESTORE_SCRIPT}" >>$LOGFILE 2>/dev/null

    if [ $? -ne 0 ]; then
       echolog "Failed to perform restore from online backup."
       /usr/bin/rm -f ${RESTORE_SCRIPT}
       /usr/bin/rm -f $oratmp
       return 1
    fi
  
    /usr/bin/rm -f ${RESTORE_SCRIPT}
    /usr/bin/rm -f $oratmp
    return 0

}

#
# Restore from export
#
check_db_sanity () {
    #
    # Check the sanity of the database. If we cannot shutdown or restart we
    # will perform a full recovery (VSANITY=1)
    #
    if [ "$FORCE" -ne 1 ]; then
        /usr/bin/su - smcorau -c "$BASEDIR/sbin/db-start" 2>/dev/null 1>&2
        if [ $? -ne 0 ]; then
            VSANITY=1
        fi
        if [ "$VSANITY" -eq 0 ];then
            /usr/bin/su - smcorau -c "$BASEDIR/sbin/db-stop" 2>/dev/null 1>&2
            if [ $? -ne 0 ]; then
                VSANITY=1
	    else
		# Set this flag so next time start_db is called
		# it references a correct $DB_UP.
		DB_UP=0
            fi
	
        fi
    fi

    # Give time for database processes to stop nicely.
    sleep 5
}

recreate_database () {
    echolog ''
    echolog 'Recreating database now...'
    echolog ''

    # Try to stop Oracle processes if any of those are up.
    # If db-stop can not be executed, forcefully kill ora and lister,
    # clean up chared memeory.
    check_and_stop_listner

    clean_subdirs ${ESTBL_BASEDIR}/$ORA_DATADIR/oradata/$ORACLE_SID
    if [ $? -ne 0 ] ; then
        echolog 'Failed to clean up $2.' "${ESTBL_BASEDIR}/$ORA_DATADIR/oradata/$ORACLE_SID"
        exit 1
    fi

    # Make sure that destination directory for the datafiles exist.
    # Otherwise, database will not be recreated.
    if [ ! -d ${ESTBL_BASEDIR}/$ORA_DATADIR/oradata/$ORACLE_SID ]; then
       /usr/bin/mkdir -p ${ESTBL_BASEDIR}/$ORA_DATADIR/oradata/$ORACLE_SID
       if [ $? -ne 0 ] ; then
          echolog 'Can not create the directory $2' "${ESTBL_BASEDIR}/$ORA_DATADIR/oradata/$ORACLE_SID"
          return 1
       fi
    fi

    # Restore the oradata directory permissions
    /usr/bin/chown -R $SMCORAU:$SMCORAG "${ESTBL_BASEDIR}/$ORA_DATADIR/oradata" >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
       echolog 'Failed to restore Sun Management Center data directory permissions.'
       return 1
    fi

    /usr/bin/su - $SMCORAU -c "$DB_CRINST_SH -database" >> $LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Error while recreating database instance'
        return 1
    fi
    return 0
}

drop_database_schema () {

# Changes were made to make the schema drop more generic.
# If the script gotten to this point, the check has already been made 
# and all the users mentioned in the meta file exist in database.

for user_name in `/usr/bin/grep "_USER" $mfile | /usr/bin/cut -f2 -d= `; do

 db_dropUser "$user_name" "$SYS_LOGIN" "$SYSPWD" "$LOGFILE"

 if [ $? -ne 0 ] ; then
   echolog 'Unable to drop $2 schema.' "$user_name"
   return 1
 fi

done

return 0
}

# restore_db_perms $login $passwd $filename
restore_db_perms () {
    login=$1
    passwd=$2
    filename=$3

    $SQLPLUS /nolog <<EOF >>$LOGFILE 2>&1
	connect $login/$passwd
	whenever sqlerror exit failure
	@@$filename
EOF
    return $?
}

#
# Import Sun Management Center data back into database.
#
do_import ()
{
    retstat=0
    outfile=/tmp/ora_out.$$

    pipe=/tmp/pipe.$$

    create_pipe $pipe
    if [ $? -ne 0 ] ; then
        return 1
    fi

    /usr/bin/cat $BAK_SRC_CHUNKS | $ZCAT_CMD - > $pipe 2>/dev/null &
    pipepid=$!

    # NOTE: security issue with password on command-line.
    $DBIMP ${SYS_LOGIN}/${SYSPWD} full=y file=$pipe buffer=64000 2>$outfile 1>&2
    retstat=$?

    ora_scan_import_log $outfile
    if [ $? -ne 0 -o "$retstat" -ne 0 ]; then
        echolog "Error importing data into database"
        retstat=2
    fi 

    /usr/bin/rm -f $outfile $pipe 2>/dev/null 1>&2
    /usr/bin/kill $pipepid 2>/dev/null 1>&2

    # Restore SYS grants
    if [ -f "$BACKUPDIR/data/sysperms.sql" ] ; then
        restore_db_perms $SYS_LOGIN $SYSPWD $BACKUPDIR/data/sysperms.sql
        retstat=$?
    else
        echolog 'WARNING: database permissions were not saved as part of this backup.'
        echolog 'Some components may fail after the restore.'
    fi

    return $retstat
}

#
# Restore from export
#
restore_export () {

    echolog 'Preparing Sun Management Center database for recovery...'
    check_db_sanity

    # Deconfigure PRM if we're importing a non-PRM backup into a PRM installation.
    if [ "$RESETUP_PRM" -eq 1 ] ; then
        unsetup_cmd=${ESCOM_BASEDIR}/SUNWsymon/addons/PRM/sbin/db-unsetup.sh
        resetup_cmd=${ESCOM_BASEDIR}/SUNWsymon/addons/PRM/sbin/db-setup.sh

        if [ ! -x "$unsetup_cmd" -o \
             ! -x "$resetup_cmd"    ] ; then
            echolog 'Unable to locate PRM maintenance utilities.'
            echolog 'Cannot safely continue with restore.'
            print_failure_and_exit 1
        fi

        # Remove PRM database, but keep tablespaces.
        $unsetup_cmd -k >>$LOGFILE 2>&1
        if [ $? -ne 0 ] ; then
            echolog 'Failed to discard PRM database.'
            echolog 'You may need to re-setup PRM before restarting Sun Management Center.'
            print_failure_and_exit 1
        fi
    fi

    #
    # Prepare for export: make sure we have a clean, sane, empty database
    # before we import anything.
    #
    if [ $FORCE -eq 1  -o  $VSANITY -eq 1 ] ; then
        #
        # DB is currently in a bad state. Rebuild it from scratch.
        #
        recreate_database
        if [ $? -ne 0 ] ; then
            return 1
        fi
        start_db
    else
        #
        # DB appears to be in consistent state. Drop all existing data to
        # prepare for import.
        #
        start_db
	check_backup_compatibility
        drop_database_schema
        if [ $? -ne 0 ] ; then
            print_failure_and_exit 1
        fi
    fi

    #
    # Do the import
    #
    echolog 'Restoring backup data...'

    do_import
    if [ $? -ne 0 ] ; then
        echolog 'Import failed.'
        return 1
    fi

    # Re-configure PRM if we have just imported a non-PRM backup into a PRM
    # installation.
    if [ "$RESETUP_PRM" -eq 1 ] ; then
        if [ ! -x "$resetup_cmd" ] ; then
            echolog 'PRM setup utility missing or cannot be executed. Aborting.'
            echolog 'PRM may be in an unusable state. You must manually re-setup PRM before restarting Sun Management Center.'
            print_failure_and_exit 1
        fi

        # Re-setup PRM, -f forces reuse of existing tablespaces.
        $resetup_cmd -f >>$LOGFILE 2>&1
        if [ $? -ne 0 ] ; then
            echolog 'PRM re-setup failed. You may need to re-install PRM before it can be used.'
            print_failure_and_exit 1
        fi
    fi

    return 0
}

#
# Restore cfg files
#
restore_cfg () {
    $ZCAT_CMD $CFGBAKFILE | /usr/bin/tar xvphf - >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Failed to restore configuration files from $2.' "$CFGBAKFILE"
        return 1
    fi

    return 0
}

#
# Backward compatibility code
#
restore_old () {
    # NOTE: should clean out old files here (see 3.0 code)

    # Restore cfg files (Note: this follows the sequence in the old code. We
    # maintain this to avoid problems caused by any unexpected dependencies.)
    CFG_ARCHIVE=$BACKUPDIR/cfg.tar.Z
    /usr/bin/zcat $CFG_ARCHIVE | /usr/bin/tar xvhf - >>$LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'Failed to restore Sun Management Center configuration from $2' "$CFG_ARCHIVE"
        return 1
    fi

    # Import Sun Management Center data
    DB_ARCHIVE=$BACKUPDIR/sunmc.dmp
    start_db
    $DBIMP ${SYS_LOGIN}/${SYSPWD} full=y file=$DB_ARCHIVE 2>$outfile 1>&2
    if [ $? -ne 0 ] ; then
        echolog 'Database import failed'
        return 1
    fi

    return 0
}

ask_for_backup_dir () {
    # Get backup directory from user
    backupdir_flag=""
    while [ "$backupdir_flag" = "" ]
    do
        get_input_from_user 'Enter full directory path where the backup data files reside [$BACKUPDIR]:' 
        if [ -z "$answer" ] ; then
            #
            # use default backup directory
            #
            backupdir_flag="done"
        else
            /bin/echo "$answer" | /usr/bin/grep "^/" > /dev/null 2>&1
	    if [ $? -ne 0 ] ; then
                echolog "The backup directory path must start with /"
                continue
            fi

            /bin/echo "$answer" | /usr/bin/grep " " > /dev/null 2>&1 
            if [ $? -eq 0 ] ; then
                echolog "Invalid directory name"
                continue
            fi

            if [ "$answer" = "/" ] ; then
                echolog "Invalid directory name: /"
                continue
            fi

            if [ ! -d $answer ] ; then
                echolog 'The directory $2 does not exist.' "$2"
                continue
            fi

            backupdir_flag="done"
            BACKUPDIR="$answer"
        fi
    done
}


###############################################
#
#   Main entry point
#
prog_base=`/usr/bin/basename $0`
common_cmd=`/bin/echo $0 | /usr/bin/sed s/$prog_base/es-common.sh/`
. $common_cmd

set_basedir
set_db_env
set_commondirs

NLS_LANG=AMERICAN_AMERICA.UTF8; export NLS_LANG

check_root

# Initialize es-restore environment
shared_cmd=`/bin/echo $0 | /usr/bin/sed s/$prog_base/es-backup-common/`
. $shared_cmd

check_logfile restore
export LOGFILE

set_backup_common
if [ $? -ne 0 ] ; then
    echolog $errormsg
    print_failure_and_exit 1
fi

cd "$BASEDIR"
PWD="$BASEDIR"; export PWD
PROGNAME=$0; export PROGNAME

DBIMP=$ORACLE_HOME/bin/imp


# Set FORCE=1 to force re-creation of database schema.
# By default, this is done only when something is wrong with the database
# (VSANITY=1).
FORCE=0
VSANITY=0

umask 022

ESDIR=${ESDIR-/var/opt/SUNWsymon}
BACKUPDIR=${ESDIR}/backup

#
# Parse command-line options
#
interactive=1
while getopts cd:fyvh OPT ; do
    case $OPT in
        c)
            CHECK_ONLY=1
            ;;
        d)
            BACKUPDIR=$OPTARG
            ;;
        f)
            FORCE=1
            ;;
        y)
            interactive=0
            ;;
        v)
            VERBOSE=ON
            ;;
        h)
            /bin/echo ""
            print_usage
            exit 1
            ;;
        *)
            /bin/echo ""
            print_usage
            exit 1
            ;;
    esac
done


#
# Make sure that we only have one instance of es-backup/es-restore running.
#
check_process_conflicts es-restore
if [ $? -ne 0 ] ; then
    echolog 'Conflicting process found: es-restore'
    echolog 'Only one instance of es-restore should be running at a time.'
    print_failure_and_exit 1
fi

check_process_conflicts es-backup
if [ $? -ne 0 ] ; then
    echolog 'Conflicting process found: es-backup'
    echolog 'es-restore should not be run at the same time as es-backup.'
    print_failure_and_exit 1
fi


#
# Validation only
#
if [ "$CHECK_ONLY" ] ; then
    echolog 'Validating backup data only...'
    echolog ''
    if [ $interactive -eq 1 ] ; then
        ask_for_backup_dir
    fi

    echolog 'Validating backup data in $2' "$BACKUPDIR"
    read_metafile
    check_backup_compatibility
    validate_backup
    if [ $? -eq 0 ] ; then
        echolog 'Backup validation successful.'
        exit 0
    fi
    echolog 'Backup validation failed.'
    exit 1
fi

#
# Stop Sun Management Center and obtain backup dir
#

if [ "$interactive" -eq 0 ] ; then
    #
    # Non-interactive mode
    #
    echolog ""
    echolog "Shutting down Sun Management Center."
    stop_SunMC
    if [ $? -ne 0 ] ; then
        print_failure_and_exit 1
    fi

    if [ ! -d $BACKUPDIR ] ; then
        echolog 'Unable to find backup data in $2' "$BACKUPDIR"
        exit 1
    fi

else
    #
    # Interactive mode
    #
    echolog ""
    echolog 'Sun Management Center must be shutdown to restore data.'
    get_input_from_user "Do you want to proceed [y/n]:"
    if [ "$answer" = "y" ] ; then
        stop_SunMC
        if [ $? -ne 0 ] ; then
            print_failure_and_exit 1
        fi
    else
        exit 0
    fi

    ask_for_backup_dir
fi

#
# Examine backup directory and make sure it contains valid backup data and
# is compatible with the current SunMC installation.
#
echolog 'Validating Sun Management Center backup data in $2' "$BACKUPDIR"
read_metafile
validate_backup
if [ $? -ne 0 ] ; then
    print_failure_and_exit 1
fi

#
# Restore the backup data now
#

echolog 'Restoring Sun Management Center data from backup. Please wait...'
if   [ "$BACKUP_FORMAT" -eq 0 ] ; then
    # Backward compatibility code.

    # Note: this will also restore cfg files from the old backup. The old
    # cfg files archive isn't handled properly by restore_cfg.
    restore_old
    if [ $? -ne 0 ] ; then
        print_failure_and_exit 1
    fi
else
    if [ "$BACKUP_FORMAT" -eq 1 ] ; then
        restore_cold
        if [ $? -ne 0 ] ; then
            print_failure_and_exit 1
        fi
    elif [ "$BACKUP_FORMAT" -eq 2 -o "$BACKUP_FORMAT" -eq 4 ] ; then
        restore_export
    elif [ "$BACKUP_FORMAT" -eq 3 ] ; then
        restore_online
    fi
    if [ $? -ne 0 ] ; then
        print_failure_and_exit 1
    fi

    #
    # Restore configuration files
    #

    restore_cfg
    if [ $? -ne 0 ] ; then
        print_failure_and_exit 1
    fi
fi

# Prevent any potential conflicts with es-start -A.
shutdown_db


#
# Re-start SunMC server
#

echolog 'Backup restored successfully.'
if [ "$BACKUP_FORMAT" -eq 3 ] ; then
    echolog ' '
    echolog 'It is recommended to take a fresh backup using es-backup -o.'
    echolog ' '
fi

if [ $interactive -eq 1 ] ; then

   ask_user 'Do you want to start Sun Management Center agent and server components now '

   if [ $answer -eq 1 ] ; then
      echolog 'Re-starting Sun Management Center...'
      $BASEDIR/sbin/es-start -A
      if [ $? -ne 0 ] ; then
          echolog 'Failed to restart Sun Management Center.'
          exit 1
      fi
   fi

else

   echolog 'Re-starting Sun Management Center...'
   $BASEDIR/sbin/es-start -A
   if [ $? -ne 0 ] ; then
       echolog 'Failed to restart Sun Management Center.'
       exit 1
   fi

fi

exit 0

