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

##### TITLE DEFINE ###############################
SECUREMATRIX="SECUREMATRIX"

##### ENV SET #############################
# ENV PARAM read
. ${INST_HOME}/define.sh

#LANG=C;LANGUAGE=C;
#export LANG LANGUAGE

##### DECIDE MSG PROP #####################
. ${MSG_PROP}

##### Function ###################################
#----- display clear ----------------------------#
CLEAR(){
  $clear
}

#----- wait ENTER input -------------------------#
WAIT_ENTER(){
  $echo "<<< ${PLEASE_ENTER} >>>"
  read enter
}

#----- Quit Process -----------------------------#
quit(){
  $echo " "
  $echo "${SMX_INST_QUIT}"
  write_log "${SMX_INST_QUIT}"
  arize_err "dmy" "${SMX_INST_QUIT}"
  exit 1
}

#----- check root_user -------------------------#
check_root(){
  RTC=/tmp/rootchecker
  touch $RTC > /dev/null 2>&1
  chown root:root $RTC > /dev/null 2>&1
  if [ $? = 1 ] ; then
    $rm -f $RTC > /dev/null 2>&1
    $echo ""
    $echo "${WARNING}: ${ROOTUSER_EXCUTE}"
    $echo ""
    exit 1
  fi
  $rm -f $RTC > /dev/null 2>&1
  return 0
}

#----- init ---------------------------------#
initialize(){
  if [ -z "`$echo -n`" ] ; then
      ECHO_SP1=-n
      ECHO_SP2=
  else
      ECHO_SP1=
      ECHO_SP2='\c'
  fi
  
  # patch_installer info read
  getPII
}

#----- CurrentDirectory check -------------------#
current_dir_check(){
  if [ `pwd` != "${INST_HOME}" ] ; then
    $echo "ERROR !"
    $echo ""
    msg_err "ERR: ${CURRENTDIR_ERR}" \
            " " \
            "${INST_DIRMOVE_EXCUTE}" \
            " "
    exit 1
  fi
}

#----- wait input type echo ---------------------------#
echo_sp(){
    $echo $ECHO_SP1 "$@" $ECHO_SP2
}

#----- error output log ---------------------------#
arize_err(){        # args:error_code, message
  add_msg=$2                                  # message
  DATE=`$date '+ %F %T '`
  $echo "[${DATE}] ${add_msg}" >> $ERR_LOG_FILE
}

#----- output log ---------------------------------#
write_log(){        # args:message
  MSG=$1
  DATE=`date '+ %F %T '`
  $echo "[${DATE}] ${MSG}" >> $LOG_FILE
}

#----- SMX param setting read --------------#
load_setup_properties(){
  
ORG_IFS=$IFS
IFS='
'
  LOAD_FILE=$SETUP_PROPERTIES_FILE
  
  if [ -s $LOAD_FILE ] ; then
    for LINE in `$cat $LOAD_FILE | grep -v '^#' | grep -v '^$'`
    do
      eval $LINE 1> /dev/null 2>> ${ERR_LOG_FILE}
      if [ $? -ne 0 ] ; then
        arize_err "FNC002" "File. [$LOAD_FILE]"
        $echo ""
        msg_err "${SETTING_INFOFILE_READ_MISS}" "${PROSECC_QUIT}" " " "[ ${READ_MISS_SETTINGFILE} ]" "---------------------------------------------------------------------------" "${LOAD_FILE}"
        exit 1
      fi
    done
  else
    # setting file lost when output error_log
    $echo "!!! ${NOEXIST_SETUP_PROPS} [$LOAD_FILE] !!!"
    arize_err "dmy" "!!! ${NOEXIST_SETUP_PROPS} [$LOAD_FILE] !!!"
  fi
IFS=$ORG_IFS
}

#----- install info read ----------------------------#
getPII(){
  # Version from define.sh
  NOW_SMX_DETAIL_VERSION="${TO_VER}"
  
  # Server info from SMX_INFO
  eval `$cat ${INST_HOME}/SMX_INFO | $grep SVR_FULL` ;
  NOW_SMX_SVR_FULL="${SVR_FULL}"
}

#----- Only msg_*** type message output ---------------------------------#
echo_for_msg(){   # args:message, frame
  MSG="$1"
  LINE_CHAR="$2"
  
  if [ -n "$MSG" -a "$MSG" != "" ] ; then     # when exist message, output
    #WC=`$echo "$MSG" | $wc -c`               # (Only EUC) Message span (WorcCount...accualy + 1)
    $echo "${MSG}" > TMP                      # (Only UTF-8) nkf is only file, therefore output file
    WC=`$NKF_PATH --euc TMP | wc -c`          # (Only UTF-8) Message span: UTF-8 Japanese is 3byte, therefore euc change 2byte (wc is only 2byte)
    $rm -f TMP > /dev/null 2>&1
    SP_NUM=`expr 76 - $WC`                    # Number of needed space(79char - left2char - WC - 1)
    SP_CNT=0
    SP_STR=""
    while [ $SP_NUM -gt $SP_CNT ]
    do
      SP_STR=${SP_STR}" "                               # space create
      SP_CNT=`expr $SP_CNT + 1`
    done
    $echo "${LINE_CHAR} ${MSG}${SP_STR} ${LINE_CHAR}"    # output
  fi
}

#----- standard output ------------------------------------------#
msg_info(){  # args:message(1-8)
#  echo ""
  $echo "+-----------------------------------------------------------------------------+"
  echo_for_msg "${SECUREMATRIX} Patch Installer  /  ${NOW_SMX_SVR_FULL}  /  Version ${NOW_SMX_DETAIL_VERSION}" "|"
  $echo "|-----------------------------------------------------------------------------|"
  i=1
  while [ $i -le 21 ]                           # Max 21 line
  do
    eval MSG=\${$i}
    echo_for_msg "$MSG" "|"
    i=`expr $i + 1`
  done
  $echo "+-----------------------------------------------------------------------------+"
  $echo ""
}

#----- error output ----------------------------------------#
msg_err(){  # args:message(1-8)
#  echo ""
  $echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
  echo_for_msg "${SECUREMATRIX} Error!! / ${NOW_SMX_SVR_FULL} / Version ${NOW_SMX_DETAIL_VERSION}" "*"
  $echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
  i=1
  while [ $i -le 21 ]                           # Max 21 line
  do
    eval MSG=\${$i}
    echo_for_msg "$MSG" "*"
    i=`expr $i + 1`
  done
  
  $echo "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
  $echo ""
  
}

#----- standard dialog output ------------------------------------------#
msg_dialog(){  # args:message(1-8)
#  echo ""
  $echo "+-----------------------------------------------------------------------------+"
  i=1
  while [ $i -le 21 ]                           # Max 21 line
  do
    eval MSG=\${$i}
    echo_for_msg "$MSG" "|"
    i=`expr $i + 1`
  done
  $echo "+-----------------------------------------------------------------------------+"
  $echo ""
}

#----- allow version of patch install ----------------------------#
get_patch_scope(){    # args : MSG_CHAR , HEADER_CHAR
  MSG_CHAR="$1"        # need space of head
  HEADER_CHAR=" $2"     # need space of head
  RESPONSE_STR=""
  
  AWKNUM=`$echo $SCOPE_VER | awk '{print NF}'`
#debug#  echo $AWKNUM
  CNT=0
  while [ $CNT -ne $AWKNUM ]
  do
    CNT=`expr $CNT + 1`
    if [ $CNT -eq 1 ] ; then
      TMP_VER_STR=`$echo $SCOPE_VER | awk '{print $'$CNT'}'`
      RESPONSE_STR="${MSG_CHAR}Ver-${TMP_VER_STR}"
    else
      TMP_VER_STR=`$echo $SCOPE_VER | awk '{print $'$CNT'}'`
      RESPONSE_STR="${RESPONSE_STR}${HEADER_CHAR}Ver-${TMP_VER_STR}"
    fi
  done
  $echo "$RESPONSE_STR"
}

#----- Search admin.properties of FQDN -----------#
getFQDN(){
  if [ -f ${ADMIN_PROPERTIES_FILE} ] ; then
    PriFQDN=`$cat ${ADMIN_PROPERTIES_FILE} | $grep ^"AUTH1_FQDN" | $awk -F'=' '{print $NF}'`
    SecFQDN=`$cat ${ADMIN_PROPERTIES_FILE} | $grep ^"AUTH2_FQDN" | $awk -F'=' '{print $NF}'`
    ownFQDN=`$cat ${ADMIN_PROPERTIES_FILE} | $grep ^"ADMIN_FQDN" | $awk -F'=' '{print $NF}'`
    if [ "${ownFQDN}" = "${PriFQDN}" ] ; then
      brsFQDN="${SecFQDN}"
    else
      brsFQDN="${PriFQDN}"
    fi
  else
    arize_err "dmy" "ERROR : No file exist! [ ${ADMIN_PROPERTIES_FILE} ]"
    msg_err "${SETTING_INFOFILE_READ_MISS}" \
            "${PROSECC_QUIT}" \
            " " \
            "[ ${READ_MISS_SETTINGFILE} ]" \
            "---------------------------------------------------------------------------" \
            "${ADMIN_PROPERTIES_FILE}"
    exit 1
  fi
}

#----- Cluster check --------------------------------------------#
get_auth_cluster_mode(){
  # Search admin.properties of Auth2_FQDN
  # return:1=single , 2=cluster
  getFQDN
  if [ -z "${SecFQDN}" ] ; then
    # Auth2_FQDN is null > single
    return 1
  else
    # cluster
    return 2
  fi
}

#----- judge primary auth ------------------------------------------#
isPrimaryAuth(){
  # judge Cluster from admin.properties 
  # judge myself is primary auth
  # return 0=myself_primary , 1=myself_secondary
  getFQDN
  if [ "${ownFQDN}" = "${PriFQDN}" ] ; then
    # AdminFQDN = PrimaryFQDN -> myself primary
    return 0
  else
    # else secondary
    return 1
  fi
}

#----- Radius check ---------------------------------------------#
isUseRadius(){
  # Search service_list
  # return:0=use , 1=deny
  $cat ${SMX_SERVICE_LIST_FILE} | $grep ^'Radius' 1> /dev/null 2>> ${ERR_LOG_FILE}
  if [ $? -eq 0 ] ; then
    # Dont comment_out Radius at service_list > use
    return 0
  else
    # deny
    return 1
  fi
}

#----- patch install miss back module ------------------------------#
back_module(){
  ##### TRAP #######################################
  # Deny Ctrl+C
  trap 'echo "Deny Ctrl+C"' 1 2 3 15

  # back module from backup_file
  $echo "${MODULE_INSTBEFORE_BACK}"
  arize_err "dmy" "${MODULE_INSTBEFORE_BACK}"
  if [ -f $BACKUP_PKG_FILE ] ; then
    $tar $X_OPT $BACKUP_PKG_FILE -C / 1> /dev/null 2>> ${ERR_LOG_FILE}
    if [ $? -ne 0 ] ; then
      arize_err "dmy" "${BACKUP_DECOMP_MISS}"
      $echo "${BACKUP_DECOMP_MISS}"
      $echo "<!> ${NOEXPECT_ERROR_SAPORT}"
      return 1
    fi
    ## Delete NEW_ADDFILE
    # GET new_addlist(from backup)
    ADDED_LIST_FILE_SP=`echo "$ADDED_LIST_FILE" | $sed -e s/^'\/'/''/g`
    $tar $X_OPT $BACKUP_PKG_FILE -C / $ADDED_LIST_FILE_SP 1> /dev/null 2>> ${ERR_LOG_FILE}
    if [ $? -ne 0 ] ; then
      arize_err "dmy" "${GET_NEW_ADDFILELIST_MISS}"
      $echo "${GET_NEW_ADDFILELIST_MISS}"
      $echo "<!> ${NOEXPECT_ERROR_SAPORT}"
      return 1
    fi
    IFS_ORG=$IFS
    IFS='
'
    for DEL_FILE in `$cat /${ADDED_LIST_FILE_SP} | grep -v '^#' | grep -v '^$'`
    do
      # Target exist addlist -> new_file -> delete
      arize_err "dmy" "[ ${DEL_FILE} ] ${DELETE_MSG}"
      $rm -f $DEL_FILE 1> /dev/null 2>> ${ERR_LOG_FILE}
      if [ $? -ne 0 ] ; then
        arize_err "dmy" "${NEWADDLIST_DELETE_MISS}"
        $echo "${NEWADDLIST_DELETE_MISS}"
        $echo "<!> ${NOEXPECT_ERROR_SAPORT}"
        return 1
      fi
    done
    IFS=$IFS_ORG
  else
    arize_err "dmy" "${BACKUP_NOEXIST}"
    $echo "${BACKUP_NOEXIST}"
    $echo "<!> ${NOEXPECT_ERROR_SAPORT}"
    return 1
  fi
  ##### TRAP #######################################
  # allow Ctrl+C
  trap 1 2 3 15
}

#----- Read securematrix_infomartion.txt ---------------------#
getSMXINFO(){
  if [ -f ${SMX_INFO_TXT_FILE} ] ; then
    eval `$cat ${SMX_INFO_TXT_FILE} | grep DISTRIBUTION_MINI`
    getSItmp=${DISTRIBUTION_MINI}
    NOW_SMX_DIST=`$echo ${getSItmp}`
    
    eval `$cat ${SMX_INFO_TXT_FILE} | grep SVR_MINI`
    getSItmp=${SVR_MINI}
    NOW_SMX_SVR=`$echo ${getSItmp}`
  else
    # file not exists -> unexpected error -> set values to "UNKNOWN"
    NOW_SMX_DIST="${UNKNOWN_WORD}"
    NOW_SMX_SVR="${UNKNOWN_WORD}"
  fi
}

#----- Temporarily save the file -----#
# Parameters   1) Full path of the file to save
# Return values OK = 0, ERROR = 1
swap_file(){

  # Check parameter
  if [ ! -f "${1}" ] ; then
    arize_err "dmy" "${MSG_TARG_FILE_NOT_EXS} [ ${1} ]"
    return 1
  fi

  # backup_dir create
  if [ ! -d ${BACKUP_DIR} ] ; then
    $mkdir ${BACKUP_DIR} 1> /dev/null 2>> ${ERR_LOG_FILE}
    if [ $? -ne 0 ] ; then
      arize_err "dmy" "${BACKUP_DIR_MISS}"
      return 1
    fi
  fi

  # Save the file to a temporary location
  $cp -rf --parents "${1}" ${BACKUP_DIR}/ 1> /dev/null 2>> ${ERR_LOG_FILE}
  if [ $? -ne 0 ] ; then
    arize_err "dmy" "${MSG_TMP_FILE_SAVE_FAIL} [ ${1} ]"
    return 1
  fi
  return 0

}

#----- Restore the file that was saved in the temporary dir -----#
# Parameters   1) Full path of the file to restore
# Return values OK = 0, ERROR = 1
swap_restore(){
  # Check parameter
  if [ ! -f "${BACKUP_DIR}/${1}" ] ; then
    arize_err "dmy" "${MSG_TARG_FILE_NOT_EXS} [ ${BACKUP_DIR}/${1} ]"
    return 1
  fi
  # Restore the file to the original location
  $cp -rf ${BACKUP_DIR}/${1} ${1} 1> /dev/null 2>> ${ERR_LOG_FILE}
  if [ $? -ne 0 ] ; then
    arize_err "dmy" "${MSG_TMP_FILE_REST_FAIL} [ ${1} ]"
    return 1
  fi
  return 0
}

