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

#
# usage
#
usage()
{
  echo ""
  echo "Usage: $0 [-d <UWC-deployed-directory>] [-h] <patch-directory>\n"
  echo "This program prepares patch configuration.\n"
  echo "  Where,"
  echo "    <UWC-deployed-directory>: The directory where you have deployed or configured"
  echo "                              the Communications Express web application."
  echo ""
  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
}

validate_deployed_dir()
{
  if [ -z "$DEPLOYED_DIR" ]; then
      echo "\nERROR: UWC deployed directory cannot be blank"
      echo "\nRerun the program and specify a valid UWC deployed directory."
      exit_with_msg 31;
  else
      if [ ! -d "$DEPLOYED_DIR" ]; then
          echo "\nERROR: UWC deployed directory \"$DEPLOYED_DIR\" doesn't exists"
          echo "\nRerun the program and specify a valid UWC deployed directory."
          exit_with_msg 32;
      elif [ ! -d "$DEPLOYED_DIR/staging" ]; then
          echo "\nERROR: UWC staging directory \"$DEPLOYED_DIR/staging\" is not found"
          echo "\nRerun the program and specify a valid UWC deployed directory."
          exit_with_msg 33;
      elif [ ! -d "$DEPLOYED_DIR/WEB-INF" ]; then
          echo "\nERROR: WEB-INF directory \"$DEPLOYED_DIR/WEB-INF\" is not found"
          echo "\nRerun the program and specify a valid UWC deployed directory."
          exit_with_msg 34;
      elif [ ! -d "$DEPLOYED_DIR/WEB-INF/config" ]; then
          echo "\nERROR: UWC config directory \"$DEPLOYED_DIR/WEB-INF/config\" is not found"
          echo "\nRerun the program and specify a valid UWC deployed directory."
          exit_with_msg 35;
      elif [ \( ! -f "$DEPLOYED_DIR/WEB-INF/config/uwcauth.properties" \) -o \( ! -f "$DEPLOYED_DIR/WEB-INF/config/uwcconfig.properties" \) ]; then
          echo "\nERROR: Could not locate UWC configuration files"
          echo "\nRerun the program and specify a valid UWC deployed directory."
          exit_with_msg 36;
      fi
  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 SUNWuwc 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 patch-config 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 patch-config tool."
    log_msg ""
    exit_with_msg 22;
  fi
}

#
# patch config files
# - attempt to patch the user files, but do not actually overwrite
# - These are config files that do not have substitutions in them.
#   so they are "easier" to patch
#
patch_config() {
  log_msg "-- Patch configuration begin run..."
  log_msg "--"

  PATCH_FILES_LIST_FILE=$PATCHDIR/patchfiles.list

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

  log_msg "-- Processing the patch files listed in $PATCH_FILES_LIST_FILE ..."
  log_msg "--"

  NumberOfFilesModified=0
  NumberOfNewFiles=0

  echo "$NumberOfFilesModified" > "$Tempfile_NumFilesModified"
  echo "$NumberOfNewFiles" > "$Tempfile_NumNewFiles"

  cat $PATCH_FILES_LIST_FILE | grep "^file " |
   awk -F' ' '{print $2}' |
     while read theFile
     do
       log_msg "-- Processing $theFile"
       log_only ""

       echo $theFile | grep "^lib\/config-templates\/" 2>&1 > /dev/null

       if [ "0" = "$?" ]; then
         ShortPath=`echo $theFile | sed -e 's/lib\/config-templates\///'`

         theDestDir=`dirname $SAVEDIR/$ShortPath`
         if [ "" != "$theDestDir" ]; then
           if [ ! -d "$theDestDir" ]; then
             log_only "/bin/mkdir -p $theDestDir"
             log_only ""

             /bin/mkdir -p "$theDestDir"
           fi
         fi

         COPY_TYPE="$COPY_FILE"
         RESTORE_TYPE="$RESTORE_FILE"

         if [ -f "$DEPLOYED_DIR/$ShortPath" ]; then 
           COPY_TYPE="$COPY_FILE"
           RESTORE_TYPE="$RESTORE_FILE"

           log_only "# File to be modified."
           log_only ""

           log_only "/bin/cp -pf $DEPLOYED_DIR/$ShortPath $SAVEDIR/$ShortPath"
           log_only ""

           /bin/cp -pf $DEPLOYED_DIR/$ShortPath $SAVEDIR/$ShortPath

           NumberOfFilesModified=`expr $NumberOfFilesModified + 1`
           echo "$NumberOfFilesModified" > "$Tempfile_NumFilesModified"
         else
           COPY_TYPE="$COPY_NEW_FILE"
           RESTORE_TYPE="$REMOVE_FILE"

           log_only "# New file to be installed."
           log_only ""

           NumberOfNewFiles=`expr $NumberOfNewFiles + 1`
           echo "$NumberOfNewFiles" > "$Tempfile_NumNewFiles"
         fi

         log_only "/bin/cp -pf $basedir/$theFile $SAVEDIR/$ShortPath.new"
         log_only ""

         /bin/cp -pf $basedir/$theFile $SAVEDIR/$ShortPath.new

         log_only "echo \"$COPY_TYPE $SAVEDIR/$ShortPath.new $DEPLOYED_DIR/$ShortPath\" >> $INSTALL_LIST_FILE"
         log_only ""

         echo "$COPY_TYPE $SAVEDIR/$ShortPath.new $DEPLOYED_DIR/$ShortPath" >> $INSTALL_LIST_FILE

         log_only "echo \"$BACKUP_FILE $DEPLOYED_DIR/$ShortPath $SAVEDIR/$ShortPath.backup\" >> $BACKOUT_LIST_FILE"
         log_only ""

         echo "$BACKUP_FILE $DEPLOYED_DIR/$ShortPath $SAVEDIR/$ShortPath.backup" >> $BACKOUT_LIST_FILE

         log_only "echo \"$RESTORE_TYPE $SAVEDIR/$ShortPath $DEPLOYED_DIR/$ShortPath\" >> $BACKOUT_LIST_FILE"
         log_only ""

         echo "$RESTORE_TYPE $SAVEDIR/$ShortPath $DEPLOYED_DIR/$ShortPath" >> $BACKOUT_LIST_FILE

       else
         theDestDir=`dirname $SAVEDIR/$theFile`
         if [ "" != "$theDestDir" ]; then
           if [ ! -d "$theDestDir" ]; then
             log_only "/bin/mkdir -p $theDestDir"
             log_only ""

             /bin/mkdir -p "$theDestDir"
           fi
         fi

         COPY_TYPE="$COPY_FILE"
         RESTORE_TYPE="$RESTORE_FILE"

         if [ -f "$DEPLOYED_DIR/$theFile" ]; then 
           COPY_TYPE="$COPY_FILE"
           RESTORE_TYPE="$RESTORE_FILE"

           log_only "# File to be modified."
           log_only ""

           log_only "/bin/cp -pf $DEPLOYED_DIR/$theFile $SAVEDIR/$theFile"
           log_only ""

           /bin/cp -pf $DEPLOYED_DIR/$theFile $SAVEDIR/$theFile

           NumberOfFilesModified=`expr $NumberOfFilesModified + 1`
           echo "$NumberOfFilesModified" > "$Tempfile_NumFilesModified"
         else
           COPY_TYPE="$COPY_NEW_FILE"
           RESTORE_TYPE="$REMOVE_FILE"

           log_only "# New file to be installed."
           log_only ""

           NumberOfNewFiles=`expr $NumberOfNewFiles + 1`
           echo "$NumberOfNewFiles" > "$Tempfile_NumNewFiles"
         fi

         log_only "/bin/cp -pf $basedir/$theFile $SAVEDIR/$theFile.new"
         log_only ""

         /bin/cp -pf $basedir/$theFile $SAVEDIR/$theFile.new

         log_only "echo \"$COPY_TYPE $SAVEDIR/$theFile.new $DEPLOYED_DIR/$theFile\" >> $INSTALL_LIST_FILE"
         log_only ""

         echo "$COPY_TYPE $SAVEDIR/$theFile.new $DEPLOYED_DIR/$theFile" >> $INSTALL_LIST_FILE

         log_only "echo \"$BACKUP_FILE $DEPLOYED_DIR/$theFile $SAVEDIR/$theFile.backup\" >> $BACKOUT_LIST_FILE"
         log_only ""

         echo "$BACKUP_FILE $DEPLOYED_DIR/$theFile $SAVEDIR/$theFile.backup" >> $BACKOUT_LIST_FILE

         log_only "echo \"$RESTORE_TYPE $SAVEDIR/$theFile $DEPLOYED_DIR/$theFile\" >> $BACKOUT_LIST_FILE"
         log_only ""

         echo "$RESTORE_TYPE $SAVEDIR/$theFile $DEPLOYED_DIR/$theFile" >> $BACKOUT_LIST_FILE

       fi

       log_only ""

     done

     NUM_FILES_MODIFIED=`cat $Tempfile_NumFilesModified`
     NUM_NEW_FILES=`cat $Tempfile_NumNewFiles`
}


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

# Definitions
#
COPY_FILE=copyfile
COPY_NEW_FILE=copynewfile
BACKUP_FILE=backupfile
RESTORE_FILE=restorefile
REMOVE_FILE=removefile

# NUM_FILES_MODIFIED - number of files modified
# NUM_NEW_FILES - number of new files
#
NUM_FILES_MODIFIED=0
NUM_NEW_FILES=0

# Is log initialized
#
IS_LOG_INITIALIZED=0

# Process arguments.
# Process deployed directory.
#
OPT_D=0
while getopts d:h theOption
do
    case $theOption in
    d)
        OPT_D=1
        DEPLOYED_DIR=$OPTARG
        validate_deployed_dir;;
    h)
        usage;;
    \?)
        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

if [ "0" = "$OPT_D" ]; then
  echo 
  echo "Enter the directory where you have deployed or configured the "
  echo "Communications Express web applicatio [UWC deployed directory]: \c"
  read DEPLOYED_DIR
  validate_deployed_dir;
fi

#
# initialize logging
#
LOGFILE=$PATCHDIR/patch-config_`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 generates new patch or config files for the Communications Express"
  log_msg "To use this utility you need to be the system's root user."
  log_msg ""
  exit_with_msg 3;
fi

get_basedir

#
# save directory ---> Contains the new candidate patched files (with .new
# extension), and corresponding copy of existing file. 
# This directory will have the same directory structure as <uwc-basedir>
# These files are created and used by patch-config.
#
SAVEDIR=$PATCHDIR/save
if [ ! -d "$SAVEDIR" ]; then
 log_msg "-- Save directory \"$SAVEDIR\" doesn't exists. Creating it ..."
 log_msg "--"
 mkdir -p $PATCHDIR/save
fi

# Set install and backout list files
#
INSTALL_LIST_FILE=$SAVEDIR/install.list
BACKOUT_LIST_FILE=$SAVEDIR/backout.list

touch $INSTALL_LIST_FILE
touch $BACKOUT_LIST_FILE

/bin/cp -f /dev/null "$INSTALL_LIST_FILE"
/bin/cp -f /dev/null "$BACKOUT_LIST_FILE"

# Set temp files for file counts
#
Tempfile_NumFilesModified=/tmp/.uwc_patch_config_tempfile_NumFilesModified_`date +%Y%m%d%H%M%S`
Tempfile_NumNewFiles=/tmp/.uwc_patch_config_tempfile_NumNewFiles_`date +%Y%m%d%H%M%S`

touch "$Tempfile_NumFilesModified"
touch "$Tempfile_NumNewFiles"

# check to make sure config is accessible
#
check_configaccess
patch_config

log_msg "--"
log_msg "--"
log_msg "-- Number of modified files = $NUM_FILES_MODIFIED "
log_msg "-- Number of new files = $NUM_NEW_FILES "
log_msg "--"
log_msg "--"
log_msg "-- Please review the changes in the new patch files before installing"
log_msg "-- them by running install-newconfig program. You can review the"
log_msg "-- changes by following below steps:"
log_msg "--"
log_msg "--   * Change to \"$SAVEDIR\" directory."
log_msg "--     This directory mimics the same directory structure layout"
log_msg "--     as under the <uwc-basedir> directory; except for the files under"
log_msg "--     <uwc-basedir>/lib/config-templates directory, which are "
log_msg "--     relocated to <uwc-basedir>."
log_msg "--"
log_msg "--     Where, <uwc-basedir> is UWC package base directory \"$basedir\""
log_msg "--"
log_msg "--   * Check the difference between <file> and <file>.new"
log_msg "--     Where,"
log_msg "--       <file> is the backed up file from previous deployment"
log_msg "--              during this patch configuration"
log_msg "--       <file>.new is the new patch file that will be supplied into"
log_msg "--                  your deployment when you run install-newconfig program."
log_msg "--"
log_msg "--"
log_msg "-- Please run install-newconfig program to apply the new patch files."
log_msg "-- And restart your web container for the changes to take effect."
log_msg "--"
echo ""
echo "For more details, please check the log file availablte at $LOGFILE "
echo ""


# Cleanup
#
/bin/rm -f "$Tempfile_NumFilesModified"
/bin/rm -f "$Tempfile_NumNewFiles"

# Save status
#
echo "patch-config=DONE" > "$SAVEDIR/.patch-config.status"

exit 0
