#!/bin/sh
# Finalize
# ---------------------------------------------- #

##### Main routine ###############################

# Function read
. ${INST_HOME}/function.sh

##### TRAP #######################################
# Deny Ctrl+C
trap 'echo "Deny Ctrl+C"' 1 2 3 15

# init
initialize

# result init
FLAG=0

# ----- functions ----- #
delete_installers_install_info_ini(){
  # Delete installer of [ install_information.ini ]
  # Configure.sh display version change
  $rm -rf ${INSTALLERS_INSTALL_INFO_INI_FILE}  1> /dev/null 2>> ${ERR_LOG_FILE}
  echo_sp "."
}

delete_install_ini(){
  # Delete ${INST_HOME}/install.ini
  $rm -rf ${INSTALL_INI}  1> /dev/null 2>> ${ERR_LOG_FILE}
  echo_sp "."
}

# backup_module rename
# When retry patch_install, backup double
backup_module_swap(){
  $mv $BACKUP_PKG_FILE $BACKUP_PKG_FILE_BAK  1> /dev/null 2>> ${ERR_LOG_FILE}
}

# SMX patch and update history since Ver-3.3.0
# separate [,]
# 1: Patch name or Updater name
# 2: install flag [1=install, 0=uninstall]
# 3: install date
# 4: uninstall date
# Describe since the second times to another line.
inst_history_write(){
  DATE=`$date '+%F %T'`
  if [ -f "${SMX_HIST}" ] ; then
    $echo "${VER_HIST_NAME}, 1, $DATE, null" 1>> ${SMX_HIST}
  else
    arize_err "dmy" "${HISTRY_WRITE_MISS}"
    FLAG=1
  fi
  echo_sp "."
}

uninst_history_write(){
IFS='
'
  DATE=`$date '+%F %T'`
  # every one line
  #
  HIST_LINE=`$cat ${SMX_HIST} 2>> ${ERR_LOG_FILE}`
  if [ $? -ne 0 -o ! -f "${SMX_HIST}" ] ; then
    arize_err "dmy" "${HISTORY_READ_MISS}"
    FLAG=1
  fi
  for LINE in `$cat ${SMX_HIST}`
  do
    $echo "${LINE}" | $grep "${VER_HIST_NAME}" > /dev/null
    if [ $? -eq 0 ] ; then
      $echo "${LINE}" | $sed -e s/"${VER_HIST_NAME}, 1"/"${VER_HIST_NAME}, 0"/g -e s/"null"/"${DATE}"/g >> SMX_HIST_TMP
    else
      $echo "${LINE}" >> SMX_HIST_TMP
    fi
  done

  $mv SMX_HIST_TMP ${SMX_HIST}  1> /dev/null 2>> ${ERR_LOG_FILE}
  echo_sp "."
}

# -------------------- #

# START
echo_sp "${FINAL_PROCESS}."
write_log "${FINAL_PROCESS_START}"

# FINAL PROCESS
# delete install_information.ini file
delete_installers_install_info_ini

if [ "${UN}" = "" ] ; then
  # Install final
  inst_history_write
elif [ "${UN}" = "${UN_MSG}" ] ; then
  # UnInstall
  delete_install_ini
  backup_module_swap
  uninst_history_write
else
  FLAG=1
fi

ORG_IFS=$IFS
IFS=' '

# result
if [ $FLAG -eq 0 ] ; then
  $echo "${END}"
  write_log "${FINAL_PROCESS_END}"
else
  $echo "${OCCURED_ERROR}"
  $echo ""
  msg_err "${FINAL_PROCESS_MISS}${PROSECC_QUIT}" \
          " " \
          "<!> ${NOEXPECT_ERROR_SAPORT}"
  arize_err "dmy" "${FINAL_PROCESS_MISS}"
fi

IFS=$ORG_IFS

exit $FLAG
