#!/bin/sh
#set -x
#
# Backout the new configuration files
# takes one argument - the PATCHDIR, typically underinstall/patch/<patchnum>
#

#
# usage
#
usage()
{
  echo ""
  echo "Usage: $0 [-R <root_dir> (Only for Solaris)] [-h] <patch-directory>\n"
  echo "This program backouts the new patch configuration from UWC deployment.\n"
  echo "  Where,"
  echo "   <root_dir>:	client_root_path is the directory that contains the bootable "
  echo "   root of a client from the server's perspective."
  echo "   client from the server's perspective. Specify client_root_path as the"
  echo "   absolute client_root_path as the absolute path name to the beginning"
  echo "   of the directory tree under which all patch files generated by "
  echo "   patchadd are to be located"
  echo "    <patch-directory>: The patch directory area created during patchaadd."
  echo "                       e.g. $basedir/install/patch/116568-05"
  echo ""
  echo "    -h : prints help"
  echo ""
  exit 1
}

exit_with_msg()
{
  ExitCode=1
  ExitMessage="\nExiting ..."
  if [ "" != "$*" ]; then
    ExitCode="$*"
    ExitMessage="\nExiting with status=$* ...\n"
  fi

  if [ "0" = "$IS_LOG_INITIALIZED" ]; then
    echo "$ExitMessage"
    exit "$ExitCode"
  else
    log_msg "$ExitMessage"
    exit "$ExitCode"
  fi
}

#   
# initialize LOGFILE
#
log_init()
{
  touch $LOGFILE

  echo "============ LOGFILE started `date` ==========" >> $LOGFILE
  echo "" >> $LOGFILE

  echo Log file is: $LOGFILE
  echo ""

  IS_LOG_INITIALIZED=1
}

#
# log a message to the screen and to the LOGFILE
#
log_msg() {
  echo "$*"
  echo "$*" >> $LOGFILE
}

#
# log a message to the LOGFILE only
#
log_only() {
  echo "$*" >> $LOGFILE
}

#
# determine basedir
# - sets the variable basedir
#
get_basedir()
{
  if [ "`/bin/uname`" = "SunOS" ]; then
    basedir=`pkgparam $ROOTDIR_OPT SUNWuwc BASEDIR`
    basedir=$ROOTDIR$basedir
  else
    cur_dir=`pwd`
    cd $PATCHDIR
    tmp=`pwd`
    basedir=`echo $tmp | sed 's/\/install\/patch\/.*$//'`
    cd $cur_dir
  fi  

  if [ -z "$basedir" ]; then
    log_msg ""
    log_msg "ERROR: Could not determine pkg base directory for SUNWuwc."
    log_msg ""
    exit_with_msg 11;
  fi

  if [ ! -d "$basedir" ]; then
    log_msg ""
    log_msg "ERROR: pkg base directory for SUNWuwc \"$basedir\" doesn't exists"
    log_msg ""
    exit_with_msg 12;
  fi

  log_msg "-- Package base directory is: $basedir "
  log_msg "--"
}

#
# check to make sure config is accessible
#
check_configaccess() {
  if [ ! -d "$basedir/staging" ]; then
    log_msg "-- ERROR: Could not access the staging area \"$basedir/staging\""
    log_msg ""
    log_msg "Application is not configured."
    log_msg "Please run uwc product configuration first, then run backout-newconfig tool."
    log_msg ""
    exit_with_msg 21;
  elif [ ! -d "$basedir/WEB-INF/config" ]; then
    log_msg "-- ERROR: Could not access config directory \"$basedir/WEB-INF/config\""
    log_msg ""
    log_msg "Application is not configured."
    log_msg "Please run uwc product configuration first, then run backout-newconfig tool."
    log_msg ""
    exit_with_msg 22;
  fi
}

#
# Backout new configuration
#
backout_newconfig() {
  log_msg "-- Backout new configuration begin run..."
  log_msg "--"

  BACKOUT_LIST_FILE=$PATCHDIR/save/backout.list

  if [ \( ! -f "$BACKOUT_LIST_FILE" \) -o \( ! -r "$BACKOUT_LIST_FILE" \) ]; then
    log_msg "-- ERROR: Can't open \"$BACKOUT_LIST_FILE\" file."
    log_msg "--"
    log_msg "-- Nothing to be done regarding the backout of new configuration."
    log_msg "--"
    return
  fi

  log_msg "-- Doing the backout of files listed in $BACKOUT_LIST_FILE ..."
  log_msg "--"

  NumberOfFilesBackedup=0
  NumberOfFilesRestored=0
  NumberOfFilesRemoved=0

  echo "$NumberOfFilesBackedup" > "$Tempfile_NumBackupFiles"
  echo "$NumberOfFilesRestored" > "$Tempfile_NumRestoredFiles"
  echo "$NumberOfFilesRemoved" > "$Tempfile_NumRemovedFiles"

  cat $BACKOUT_LIST_FILE | egrep "^$BACKUP_FILE |^$RESTORE_FILE |^$REMOVE_FILE " |
     while read theFile
     do
       CopyType=`echo $theFile | awk -F' ' '{print $1}'`
       SourceFile=`echo $theFile | awk -F' ' '{print $2}'`
       DestFile=`echo $theFile | awk -F' ' '{print $3}'`
       
       if [ "$BACKUP_FILE" = "$CopyType" ]; then

         log_msg  "-- Taking_Backup : $DestFile" 
         log_only ""

         log_only "/bin/cp -pf $SourceFile $DestFile"
         log_only ""

         /bin/cp -pf $SourceFile $DestFile

         NumberOfFilesBackedup=`expr $NumberOfFilesBackedup + 1`
         echo "$NumberOfFilesBackedup" > "$Tempfile_NumBackupFiles"

       elif [ "$RESTORE_FILE" = "$CopyType" ]; then
       
       shared_comp_file=`basename $DestFile`
       
       os=`uname`
       if [ "$os" = "SunOS" ]; then
          test_link=-h  
       else
          test_link=-L
       fi   
         
       # remove shared components links created in install-newconfig before restoring it.          
       case $shared_comp_file in 
                      activation.jar | dom.jar | jato.jar | ldapjdk.jar | mail.jar | xalan.jar | xtype.jar | jcapi.jar | jato.tld )
            if [ $test_link $DestFile ]; then
              /bin/rm -f $DestFile
            fi
         esac
   
       if [ -f $SourceFile ]; then    

          log_msg  "-- Restoring     : $DestFile" 
          log_only ""
          
          log_only "/bin/cp -pf $SourceFile $DestFile"
          log_only ""

          /bin/cp -pf $SourceFile $DestFile

          NumberOfFilesRestored=`expr $NumberOfFilesRestored + 1`
          echo "$NumberOfFilesRestored" > "$Tempfile_NumRestoredFiles"
       fi  

       elif [ "$REMOVE_FILE" = "$CopyType" ]; then

         log_msg  "-- Removing      : $DestFile" 
         log_only ""

         log_only "/bin/rm -f $DestFile"
         log_only ""

         /bin/rm -f $DestFile

         NumberOfFilesRemoved=`expr $NumberOfFilesRemoved + 1`
         echo "$NumberOfFilesRemoved" > "$Tempfile_NumRemovedFiles"

       fi

     done

  NUM_BACKED_UP_FILES=`cat $Tempfile_NumBackupFiles`
  NUM_RESTORED_FILES=`cat $Tempfile_NumRestoredFiles`
  NUM_REMOVED_FILES=`cat $Tempfile_NumRemovedFiles`
}


###########################################################################
#
# main program
#
###########################################################################
#

# Definitions
#
BACKUP_FILE=backupfile
RESTORE_FILE=restorefile
REMOVE_FILE=removefile

# NUM_BACKED_UP_FILES - number of backed up files
# NUM_RESTORED_FILES - number of restored files
# NUM_REMOVED_FILES - number of removed files
#
NUM_BACKED_UP_FILES=0
NUM_RESTORED_FILES=0
NUM_REMOVED_FILES=0

# Is log initialized
#
IS_LOG_INITIALIZED=0

ROOTDIR=""
ROOTDIR_OPT=""

# Process arguments.
#
while getopts hR: theOption
do
    case $theOption in
    h)
        usage;;
    R) 
        ROOTDIR=$OPTARG
        if [ -d "$ROOTDIR" ] ; then
         ROOTDIR_OPT="-R $ROOTDIR"
        fi
        ;;
    \?)
        echo "\nERROR: Invalid option"
        usage;;
    esac
done

shift `expr $OPTIND - 1`

if [ $# -ne 1 ]; then
  echo "\nERROR: Patch directory not specified"
 usage;
fi

PATCHDIR=$*

if [ ! -d "$PATCHDIR" ]; then
    echo "\nERROR: Patch directory \"$PATCHDIR\" doesn't exists"          
    echo "\nRerun the program and specify a valid patch directory"
    exit_with_msg 2;
fi
 
#
# Make sure patch-config run already
#
cat "$PATCHDIR/save/.patch-config.status" | grep "patch-config=DONE" 2>&1 > /dev/null
if [ "$?" != "0" ]; then
    echo "\nERROR: patch-config is not run."
    echo "\nIt is a requirement that \"patch-config\" program should be run"
    echo "prior to the running of this program."
    echo "\nPlease run patch-config program, and then rerun this program."
    exit_with_msg 4;
fi

#
# initialize logging
#
LOGFILE=$PATCHDIR/backout-newconfig_`date +%Y%m%d%H%M%S`.log
log_init

#
# must be root
#
set `/usr/bin/id`
if [ $1 != "uid=0(root)" ]; then
  log_msg ""
  log_msg "ERROR: Not a system's root user"
  log_msg ""
  log_msg "This utility backouts the new patch/config files from Communications Express deployement."
  log_msg "To use this utility you need to be the system's root user."
  exit_with_msg 3;
fi

get_basedir

# Set temp files for file counts
#
Tempfile_NumBackupFiles=/tmp/.uwc_backout_new_config_tempfile_NumBackupFiles_`date +%Y%m%d%H%M%S`
Tempfile_NumRestoredFiles=/tmp/.uwc_backout_new_config_tempfile_NumRestoredFiles_`date +%Y%m%d%H%M%S`
Tempfile_NumRemovedFiles=/tmp/.uwc_backout_new_config_tempfile_NumRemovedFiles_`date +%Y%m%d%H%M%S`

touch "$Tempfile_NumBackupFiles"
touch "$Tempfile_NumRestoredFiles"
touch "$Tempfile_NumRemovedFiles"

# check to make sure config is accessible
#
check_configaccess
backout_newconfig

log_msg "--"
log_msg "--"
log_msg "-- Number of files backed up = $NUM_BACKED_UP_FILES "
log_msg "-- Number of files restored = $NUM_RESTORED_FILES "
log_msg "-- Number of files removed = $NUM_REMOVED_FILES "
log_msg "--"

if [ \( "0" != "$NUM_BACKED_UP_FILES" \) -o \( "0" != "$NUM_RESTORED_FILES" \) -o \( "0" != "$NUM_REMOVED_FILES" \) ]; then
  log_msg "--"
  log_msg "-- Restart your web container for the changes to take effect."
  log_msg "--"
fi

echo ""
echo "For more details, please check the log file available at $LOGFILE "
echo ""


# Cleanup
#
/bin/rm -f "$Tempfile_NumBackupFiles"
/bin/rm -f "$Tempfile_NumRestoredFiles"
/bin/rm -f "$Tempfile_NumRemovedFiles"


exit 0
