######################################################################
# Fuctions used to execute actions and drive install flow
######################################################################

logFnBegin()
{
  echo "Info: -- Begin $1 --" >> $DEF_BES_LOG_FILE
}

logFnEnd()
{
  echo "Info: --  End  $1 --" >> $DEF_BES_LOG_FILE
}

# Installation actions

checkRootUser()
{
  logFnBegin "${FUNCNAME[0]}"
  uid=$(id -u)
  if [[ $uid != 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0100E' \"$PRODUCT_NAME\"`"
    exit 1
  fi
  logFnEnd "${FUNCNAME[0]}"
}

configureFirewallPort()
{
  logFnBegin "${FUNCNAME[0]}"
  portNumber=$1
  protocol=$2
  chain=${3:-INPUT}
  param=${4:---dport}
  proxyRc=0
  proxyCmd=""
  if [[ $FIREWALL_TYPE = ${ALLOWED_FIREWALL_TYPE[0]} ]]
  then
    isPortConfigured=$(cat /etc/sysconfig/iptables | while read line;
    do
      if [[ $line = *INPUT*$protocol*$portNumber*ACCEPT* ]]
      then
        writeMsg log "Firewall Port Configuration Already exists: $line"
        echo "true"
        break
      fi
    done)
    if [[ $isPortConfigured != "true" ]]
    then
      proxyCmd="iptables -I $chain -p $protocol $param $portNumber -j ACCEPT"
      writeMsg log "Run Firewall config command: $proxyCmd"
      $proxyCmd 2>> $DEF_BES_LOG_FILE
      proxyRc=$?
    fi
  elif [[ $FIREWALL_TYPE = ${ALLOWED_FIREWALL_TYPE[1]} ]]
  then
    queryCmd="firewall-cmd --query-port=$portNumber/$protocol"
    $queryCmd 1> /dev/null 2> /dev/null
      if [[ $? -eq 0 ]]
      then
        writeMsg log "Firewall Port Configuration Already exists: port $portNumber, protocol $protocol"
      else
        proxyCmd="firewall-cmd --add-port=$portNumber/$protocol"
        writeMsg log "Run Firewall config command: $proxyCmd"
        $proxyCmd 2>> $DEF_BES_LOG_FILE 1> /dev/null
        let "proxyRc=proxyRc+$?"
        proxyCmd="firewall-cmd --permanent --add-port=$portNumber/$protocol"
        writeMsg log "Run Firewall config command: $proxyCmd"
        $proxyCmd 2>> $DEF_BES_LOG_FILE 1> /dev/null
        let "proxyRc=proxyRc+$?"
      fi  
  fi

  logFnEnd "${FUNCNAME[0]}"
  return $proxyRc
}

configureFirewall()
{
  logFnBegin "${FUNCNAME[0]}"
  prRc=0
  if [[ $CONF_FIREWALL = "yes" ]]
  then
    if [[ $COMPONENT_SRV = "true" ]]
    then
      configureFirewallPort $BES_SERVER_PORT "tcp"
      let "prRc=prRc+$?"
      configureFirewallPort $BES_SERVER_PORT "udp"
      let "prRc=prRc+$?"
      configureFirewallPort $WEBUI_APPSERVER_PORT "tcp"
      let "prRc=prRc+$?"
    fi
    if [[ $COMPONENT_WR = "true" ]]
    then
      configureFirewallPort $WR_WWW_PORT "tcp"
      let "prRc=prRc+$?"
    fi
    if [[ $COMPONENT_WEBUI = "true" ]]
    then
      configureFirewallPort $WEBUI_PORT "tcp"
      let "prRc=prRc+$?"
      configureFirewallPort $WEBUI_REDIRECT_PORT "tcp"
      let "prRc=prRc+$?"
      if [[ $COMPONENT_SRV = "false" ]]
      then
        configureFirewallPort $MASTHEAD_PORT "udp"
        let "prRc=prRc+$?"
        configureFirewallPort $MASTHEAD_PORT "udp" "OUTPUT" "--sport"
        let "prRc=prRc+$?"
      fi
    fi
    if [[ $FIREWALL_TYPE = ${ALLOWED_FIREWALL_TYPE[0]} ]]
    then
      service iptables save > /dev/null
      let "prRc=prRc+$?"
    fi
  fi
  [ $prRc -eq 0 ] || writeMsg log "Warning: Unable to configure local OS Firewall"
  logFnEnd "${FUNCNAME[0]}"
}

extractKeyVal()
{
  logFnBegin "${FUNCNAME[0]}"
  fileName=$1
  keyName=$2
  isError=$3
  processLine="false"
  val=$(cat $fileName | while read line;
  do
    valueLine=$(echo $line)
    writeMsg log "Parameter: $valueLine"
    keyValue=$(echo $valueLine|while IFS='=' read key val
    do
      echo "$(echo $key)"
    done)
    if [[ $keyValue = $keyName ]]
    then
      paramValue=$(echo $valueLine|while IFS='=' read key val
      do
        echo "$(echo $val)"
      done)
      echo "$paramValue"
      break
    fi
  done)
  if [[ "$val" = "" ]]
  then
    if [[ "$isError" = "false" ]]
    then
      writeMsg log "Not Found Key: '$keyName' in '$fileName'"
    else
      writeMsg both "`nls_replace 'TEM0088E' \"$keyName\" \"$fileName\"`"
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$val"
}

isDB2Installed()
{
  logFnBegin "${FUNCNAME[0]}"
  isInstalled="false"
  if [[ -f "/usr/local/bin/db2ls" ]]
  then
    isInstalled="true"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$isInstalled"
}

extractDb2InstanceHome()
{
  logFnBegin "${FUNCNAME[0]}"
  db2User=$1
  extValue=`su - $db2User -c env | grep ^DB2_HOME`
  db2Home=""
  db2RootHome=""
  if [[ "$extValue" ]]
  then
    db2Home=$(echo $extValue|while IFS='=' read var value
    do
      echo "$(echo $value)"
    done)
    if [[ -d "$db2Home" ]]
    then
      db2RootHome=$(dirname "$db2Home")
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$db2RootHome"
}

extractDb2User()
{
  logFnBegin "${FUNCNAME[0]}"
  searchStr=$1
  fileName="/etc/passwd"
  processLine="false"
  val=$(cat $fileName | while read line;
  do
    if [[ $line = *$searchStr* ]]
    then
      writeMsg log "Found '$searchStr' in line: $line of $fileName"
      val=$(echo $line|while IFS=':' read user other
      do
        echo "$(echo $user)"
      done)
      echo "$val"
      break
    fi
  done)
  logFnEnd "${FUNCNAME[0]}"
  echo "$val"
}

getDb2BundledSetup()
{
  logFnBegin "${FUNCNAME[0]}"
  setup=""
  writeMsg both "`nls_replace 'TEM0143I'`"
  # Bash supports filename expansion (globbing), similar to regex matching but less powerful,
  # and we can use this feature with regular commands, like ls. The * below is a wild card.
  setup=$(ls *$DEF_DB2_SETUP_FILE 2> /dev/null | head -n 1)
  if [[ $setup = "" ]]
  then
    setup=$(ls ../*$DEF_DB2_SETUP_FILE 2> /dev/null | head -n 1)
  fi
  if [[ $setup = "" ]]
  then
    writeMsg both "`nls_replace 'TEM0136I'`"
    searchArchiveStr="../*gz"
    # This is an actual regex that only utilities like egrep understand
    searchSetupStr="$DEF_DB2_BUNDLED_FOLDER.{0,4}$DEF_DB2_SETUP_FILE"
    db2tarfile=$(ls --format="single-column" $searchArchiveStr 2> /dev/null | while read line;
    do
      writeMsg log "Analyzing archive: $line"
      setupCount=`tar -tf "$line" | egrep -m 1 "$searchSetupStr" | wc -l`
      if [[ $setupCount -eq 1 ]]
      then
        writeMsg both "DB2 archive detected: $line"
        echo "$line"
        break
      fi
    done)
    if [[ $db2tarfile != "" ]]
    then
      # We use this file to remember the names of the files we extract, because if we used a pipe |
      # to pass the file names to the next command, they would get processed on the fly, instead of
      # waiting until the extraction is complete.
      tmpFileNames=$(mktemp)
      extractDb2SetupDir="."
      isFolderNotWritable $extractDb2SetupDir
      if [[ $? -ne 0 ]]
        then
          writeMsg both "`nls_replace 'TEM0135E' \"$db2tarfile\" \"\`pwd\`\"`"
          chooseDb2extractDir
          extractDb2SetupDir=$DB2_EXTR_DIR
          writeMsg both "`nls_replace 'TEM0132I'`"
          # Wait for the extraction to complete
          tar -xvf "$db2tarfile" -C "$extractDb2SetupDir" > "$tmpFileNames"
          setup=$(egrep -m 1 "$searchSetupStr" "$tmpFileNames")
        else
          writeMsg both "`nls_replace 'TEM0132I'`"
          # Wait for the extraction to complete
          tar -xvf "$db2tarfile" > "$tmpFileNames"
          setup=$(egrep -m 1 "$searchSetupStr" "$tmpFileNames")
      fi
      rm "$tmpFileNames" 2> /dev/null
    fi
  else
    writeMsg both "`nls_replace 'TEM0144I' \"$setup\"`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$setup"
}

extractConfigKeyVal()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1
  sectionKeyName=$2
  keyName=$3
  isError=$4
  processLine="false"
  val=$(cat $configFile | while read line;
  do
    if [[ $line = *$sectionKeyName* ]]
    then
      writeMsg log "Found section: $line in '$configFile'"
      processLine="true"
    elif [[ $processLine = "true" ]]
    then
      valueLine=$(echo $line)
      if [[ -z "$valueLine" ]]
      then
        processLine="false"
      fi
      keyValue=$(echo $valueLine|while IFS='=' read key val
      do
        echo "$(echo $key)"
      done)
      if [[ $keyValue = $keyName ]]
      then
        paramValue=$(echo $valueLine|while IFS='=' read key val
        do
          echo "$(echo $val)"
        done)
        writeMsg log "Found key: $valueLine"
        echo "$paramValue"
        break
      fi
    fi
  done)
  if [[ "$val" = "" ]]
  then
    if [[ "$isError" = "false" ]]
    then
      writeMsg log "Not Found Key: '$keyName' of section '$sectionKeyName' in '$configFile'"
    else
      writeMsg both "`nls_replace 'TEM0087E' \"$keyName\" \"$sectionKeyName\" \"$configFile\"`"
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$val"
}

checkDiskFolderSpace()
{
  logFnBegin "${FUNCNAME[0]}"
  folderName=$1
  kBlocksReq=$2
  displayFolderName=$folderName
  while [[ ! -d $folderName ]]
  do
    folderName=$(dirname $folderName)
  done

  i=1
  df -Pk $folderName | while read line LINE
  do
    SEGS=($LINE)
    kBlocksAvail=${SEGS[2]}
    mountedOn=${SEGS[4]}
    if [[ i -ne 1 ]]
    then
      writeMsg log "Folder: $displayFolderName KBNeeded:$kBlocksReq KBAvail:$kBlocksAvail MountedOn: $mountedOn"
      ##return availableKBlocks requiredKBlocks mountedFileSystem
      echo "$kBlocksAvail;$kBlocksReq;$mountedOn"
    fi
  let i=i+1
  done
  logFnEnd "${FUNCNAME[0]}"
}

getDiskList()
{
  logFnBegin "${FUNCNAME[0]}"
  inputDisk=($1)
  diskList=()
  uniqueDiskList=()
  i=0
  j=0
  for input in ${inputDisk[*]}
  do
    diskList[i]=$(echo "$input"|while IFS=';' read tok1 tok2 tok3
    do
      echo "$tok3"
    done)
    let i=i+1
  done
  for disk in ${diskList[*]}
  do
    diskFound="false"
    for uniqueDisk in ${uniqueDiskList[*]}
    do
      if [[ $disk = $uniqueDisk ]]
      then
        diskFound="true"
      fi
    done
    if [[ $diskFound = "false" ]]
    then
      uniqueDiskList[j]=$disk
      let j=j+1
    fi
  done
  logFnEnd "${FUNCNAME[0]}"
  echo "${uniqueDiskList[*]}"
}

evalDiskSpace()
{
  logFnBegin "${FUNCNAME[0]}"
  diskList=$1
  diskSpaceList=($2)
  missingSpace="false"
  for disk in $diskList
  do
    neededSpace=0
    availSpace=0
    for diskSpace in ${diskSpaceList[*]}
    do
      neededSpace=$(echo "$diskSpace"|while IFS=';' read tok1 tok2 tok3
        do
          if [[ $disk = $tok3 ]]
          then
            let neededSpace=neededSpace+$tok2
          else
            neededSpace=$neededSpace 
          fi
          echo $neededSpace
        done)
      availSpace=$(echo "$diskSpace"|while IFS=';' read tok1 tok2 tok3
        do
          if [[ $disk = $tok3 ]]
          then
            availSpace=$tok1
          else
            availSpace=$availSpace
          fi
          echo $availSpace
        done)
    done

    writeMsg log "disk=$disk neededSpace=$neededSpace KByte availSpace=$availSpace KByte"
    if [[ $neededSpace -ge $availSpace ]]
    then
      writeMsg log "Warning: Not enought space in '$disk'"
      missingSpace="true"
    fi
  done
  logFnEnd "${FUNCNAME[0]}"
  echo "$missingSpace"
}

extractDb2UserFromTemplate()
{
  logFnBegin "${FUNCNAME[0]}"
  homeLine=`cat $DEF_BES_DB2_RESP_TEMPLATE | grep "^inst1.HOME_DIRECTORY"`;
  homeDir=$(echo "$homeLine"|while IFS='=' read tok1 tok2
  do
    echo "$tok2"
  done)
  logFnEnd "${FUNCNAME[0]}"
  echo $homeDir
}

checkDb2suid()
{
  logFnBegin "${FUNCNAME[0]}"
  installDir=$1
  dir=$(echo "$installDir" | awk 'BEGIN { FS = "/" } ; { print $2 }')
  nosuid=$(grep "/$dir.*nosuid" /proc/mounts)
  if [[ $nosuid != "" ]] 
  then
    writeMsg both "`nls_replace 'TEM0180E' \"$installDir\"`"
    exit 1
  fi
  logFnEnd "${FUNCNAME[0]}"
}

checkDiskSpace()
{
  logFnBegin "${FUNCNAME[0]}"
  diskSpace=()
  db2UserHome=""
  if [[ $LOCAL_DATABASE = "true" && $INSTALL_DB2 = "yes" ]]
  then
    db2UserHome=$(extractDb2UserFromTemplate)
  else
    db2UserHome=$(extractDb2InstanceHome "$DB_ADMIN_USER")
  fi

  if [[ $COMPONENT_SRV = "true" ]] || [[ $COMPONENT_WEBUI = "true" ]]
  then
    ##/var/opt/BESClient
    diskSpace[3]=$(checkDiskFolderSpace "/var/opt/BESClient" "20000")

    ##/opt/BESClient
    diskSpace[5]=$(checkDiskFolderSpace "/opt/BESClient" "40000")

    ##/etc/opt/BESClient
    diskSpace[7]=$(checkDiskFolderSpace "$DEF_AGT_ETC" "500")
  fi

  if [[ $COMPONENT_SRV = "true" ]]
  then
    ##/var/opt/BESServer
    diskSpace[0]=$(checkDiskFolderSpace "$DEF_BES_ROOT" "50000")

    ##/var/opt/BESServer/wwwrootbes
    diskSpace[1]=$(checkDiskFolderSpace "$BES_WWW_FOLDER$DEF_BES_WWW_FOLDER" "50000")

    ##/var/opt/BESInstallers
    diskSpace[2]=$(checkDiskFolderSpace "$INSTALLERS_DIR" "50000")

    ##/opt/BESServer
    diskSpace[4]=$(checkDiskFolderSpace "/opt/BESServer" "70000")

    ##/etc/opt/BESServer
    diskSpace[6]=$(checkDiskFolderSpace "$DEF_BES_ETC" "500")

    if [[ $LOCAL_DATABASE = "true" && "$db2UserHome" != ""  ]]
    then
      ##/home/<db2user>
      diskSpace[8]=$(checkDiskFolderSpace "$db2UserHome" "1000000")
    fi
  fi

  if [[ $COMPONENT_WR = "true" ]]
  then
    ##/var/opt/BESWebReportsServer
    diskSpace[9]=$(checkDiskFolderSpace "$DEF_WR_ROOT" "30000")

    ##/var/opt/BESWebReportsServer/wwwroot
    diskSpace[10]=$(checkDiskFolderSpace "$WR_WWW_FOLDER$DEF_WR_WWW_FOLDER" "150000")

    ##/opt/BESWebReportsServer
    diskSpace[11]=$(checkDiskFolderSpace "/opt/BESWebReportsServer" "40000")

    ##/etc/opt/BESWebReportsServer
    diskSpace[12]=$(checkDiskFolderSpace "$DEF_WR_ETC" "500")

    if [[ $LOCAL_DATABASE = "true" && "$db2UserHome" != "" ]]
    then
      ##/home/<db2user>
      diskSpace[13]=$(checkDiskFolderSpace "$db2UserHome" "750000")
    fi
  fi

  if [[ $LOCAL_DATABASE = "true" && $INSTALL_DB2 = "yes" ]]
  then
    ##/opt/ibm/db2/V10.5
    diskSpace[14]=$(checkDiskFolderSpace "$DB2_INSTALL_DIR" "1500000")
  fi

  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    ##/var/opt/BESWebUI
    diskSpace[15]=$(checkDiskFolderSpace "$DEF_WEBUI_ROOT" "50000")

    ##/opt/BESWebUI
    diskSpace[16]=$(checkDiskFolderSpace "/opt/BESWebUI" "70000")

    if [[ $LOCAL_DATABASE = "true" && "$db2UserHome" != ""  ]]
    then
      ##/home/<db2user>
      diskSpace[17]=$(checkDiskFolderSpace "$db2UserHome" "750000")
    fi
  fi

  diskList=$(getDiskList "${diskSpace[*]}")
  missingSpace=$(evalDiskSpace "$diskList" "${diskSpace[*]}")
  PREREQ_SPACE_MISSING="$missingSpace"
  logFnEnd "${FUNCNAME[0]}"
}

setServerEncoding()
{
  logFnBegin "${FUNCNAME[0]}"
  curr_locale=$LC_ALL
  [ "$curr_locale" ] || curr_locale=$LC_MESSAGES
  [ "$curr_locale" ] || curr_locale=$LANG
  if [[ "$curr_locale" != "" ]]
  then
    ## example curr_locale=en_US.UTF-8
    writeMsg log "Current locale: $curr_locale"
    case "$curr_locale" in
      ar*|AR*|Ar*) curr_locale="ar";;
      ca*|CA*|Ca*) curr_locale="ca";;
      cs*|CS*|Cs*) curr_locale="cs";;
      da*|DA*|Da*) curr_locale="da";;
      de*|DE*|De*) curr_locale="de";;
      el*|EL*|El*) curr_locale="el";;
      en*|EN*|En*) curr_locale="en";;
      es*|ES*|Es*) curr_locale="es";;
      et*|ET*|Et*) curr_locale="et";;
      eu*|EU*|Eu*) curr_locale="eu";;
      fi*|FI*|Fi*) curr_locale="fi";;
      fr*|FR*|Fr*) curr_locale="fr";;
      he*|HE*|He*) curr_locale="he";;
      hr*|HR*|Hr*) curr_locale="hr";;
      hu*|HU*|Hu*) curr_locale="hu";;
      it*|IT*|It*) curr_locale="it";;
      ja*|JA*|Ja*) curr_locale="ja";;
      ko*|KO*|Ko*) curr_locale="ko";;
      lt*|LT*|Lt*) curr_locale="lt";;
      lv*|LV*|Lv*) curr_locale="lv";;
      nb*|NB*|Nb*) curr_locale="nb";;
      nl*|NL*|Nl*) curr_locale="nl";;
      pl*|PL*|Pl*) curr_locale="pl";;
      pt*br*|pt*BR*|PT*BR*|Pt*BR*) curr_locale="pt_BR";;
      ro*|RO*|Ro*) curr_locale="ro";;
      ru*|RU*|Ru*) curr_locale="ru";;
      sk*|SK*|Sk*) curr_locale="sk";;
      sl*|SL*|Sl*) curr_locale="sl";;
      sv*|SV*|Sv*) curr_locale="sv";;
      th*|TH*|Th*) curr_locale="th";;
      tr*|TR*|Tr*) curr_locale="tr";;
      vi*|VI*|Vi*) curr_locale="vi";;
      zh*tw*|zh*TW*|ZH*TW*|tw*|TW*|Zh*TW*|Zh*tw*) curr_locale="zh_TW";;
      zh*|ZH*|Zh*) curr_locale="zh_CN";;
    esac
    ## example curr_locale=en
    encodeLine=`cat $DEF_BES_ENCODING_MAP_FILE | grep "^$curr_locale"`;
    ENC_VALUE=$(echo "$encodeLine"|while IFS='=' read tok1 tok2
    do
      echo "$tok2"
    done)
  fi
  if [[ $ENC_VALUE = "" ]]
  then
    writeMsg log "Warning: Server encode mapping for locale '$curr_locale' not found."
  else
    writeMsg log "The following Encoding has been detected: $ENC_VALUE"
  fi
  logFnEnd "${FUNCNAME[0]}"
}

getLAFileName()
{
  logFnBegin "${FUNCNAME[0]}"
  licFolder=$1
  LAFile="LA_en"
  curr_locale=$LC_ALL
  [ "$curr_locale" ] || curr_locale=$LC_MESSAGES
  [ "$curr_locale" ] || curr_locale=$LANG
  if [[ "$curr_locale" != "" ]]
  then
    ## example curr_locale=en_US.UTF-8
    writeMsg log "Current locale to locate license file: $curr_locale"
    case "$curr_locale" in
      ar*|AR*|Ar*) curr_locale="ar";;
      ca*|CA*|Ca*) curr_locale="ca";;
      cs*|CS*|Cs*) curr_locale="cs";;
      da*|DA*|Da*) curr_locale="da";;
      de*|DE*|De*) curr_locale="de";;
      el*|EL*|El*) curr_locale="el";;
      en*|EN*|En*) curr_locale="en";;
      es*|ES*|Es*) curr_locale="es";;
      et*|ET*|Et*) curr_locale="et";;
      eu*|EU*|Eu*) curr_locale="eu";;
      fi*|FI*|Fi*) curr_locale="fi";;
      fr*|FR*|Fr*) curr_locale="fr";;
      he*|HE*|He*) curr_locale="he";;
      hr*|HR*|Hr*) curr_locale="hr";;
      hu*|HU*|Hu*) curr_locale="hu";;
      it*|IT*|It*) curr_locale="it";;
      ja*|JA*|Ja*) curr_locale="ja";;
      ko*|KO*|Ko*) curr_locale="ko";;
      lt*|LT*|Lt*) curr_locale="lt";;
      lv*|LV*|Lv*) curr_locale="lv";;
      nb*|NB*|Nb*) curr_locale="nb";;
      nl*|NL*|Nl*) curr_locale="nl";;
      pl*|PL*|Pl*) curr_locale="pl";;
      pt*br*|pt*BR*|PT*BR*|Pt*BR*) curr_locale="pt_BR";;
      ro*|RO*|Ro*) curr_locale="ro";;
      ru*|RU*|Ru*) curr_locale="ru";;
      sk*|SK*|Sk*) curr_locale="sk";;
      sl*|SL*|Sl*) curr_locale="sl";;
      sv*|SV*|Sv*) curr_locale="sv";;
      th*|TH*|Th*) curr_locale="th";;
      tr*|TR*|Tr*) curr_locale="tr";;
      vi*|VI*|Vi*) curr_locale="vi";;
      zh*tw*|zh*TW*|ZH*TW*|tw*|TW*|Zh*TW*|Zh*tw*) curr_locale="zh_TW";;
      zh*|ZH*|Zh*) curr_locale="zh_CN";;
    esac
    ## example curr_locale=en
    LAFile="LA_$curr_locale.txt"
  fi
  if [[ -e "$licFolder/$LAFile" ]]
  then
    writeMsg log " Found LA file mapping for locale '$curr_locale'"
  else
    writeMsg log "Warning: License file mapping for locale '$curr_locale' not found, setting english LA file."
	LAFile="LA_en.txt"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$licFolder/$LAFile"
}

copyLAFiles()
{
  logFnBegin "${FUNCNAME[0]}"
  sourceLAFolder=$1
  destLAFolder=$2
  if [[ $destLAFolder != "" ]]
  then
    if [[ -d "$destLAFolder/license" ]]
    then
	    writeMsg log " $destLAFolder exist removing old LA files"
		rm -Rf "$destLAFolder/license/"*.txt
		rm -Rf "$destLAFolder/license/"LA_*
	else
		mkdir -p "$destLAFolder/license"
	fi
	cp -Rf "$sourceLAFolder"/* "$destLAFolder/license/"
  fi
  logFnEnd "${FUNCNAME[0]}"
}

extractDB2Lib64Path()
{
  logFnBegin "${FUNCNAME[0]}"
  returnPath=""
  userLibPaths=$(su - $1 -c 'echo $LD_LIBRARY_PATH')
  if [[ $? != 0 ]]
  then
    writeMsg log "Error attempting to login to '$1'"
  fi
  numOfRows=$(echo "$userLibPaths" | grep '^' | wc -l)
  if [[ $numOfRows = 0 ]]
  then
    writeMsg log "Error variable LD_LIBRARY_PATH appears empty"
  fi
  if [[ $numOfRows > 1 ]]
  then
    writeMsg log "Found $numOfRows rows, too many, so retry using 'set' ..."
    userLibPaths=$(su - $1 -c 'set' | grep -w LD_LIBRARY_PATH | cut -d'=' -f2)
  fi
  set -f; IFS=:
  for path in $userLibPaths; do
    if [[ "$(basename $path)" = "lib64" ]]
    then
      db2DriverPath="$path/$DB2_DRIVER_FILE_NAME"
      if [[ -f $db2DriverPath ]]
      then
        if [[ "$returnPath" = "" ]]
        then
          returnPath="$path"
          writeMsg log "Info: Found DB2_LIB_PATH candidate: '$path'."
        else
          writeMsg log "Warning: Found another DB2_LIB_PATH candidate: '$path'."
        fi
      elif [[ ! -e $path ]]
      then
        writeMsg log "Error: path '$path' does not exist. "
      else
        writeMsg log "Error: library '$db2DriverPath' not found. "
      fi
    fi
  done
  set =f; unset IFS
  logFnEnd "${FUNCNAME[0]}"
  echo "$returnPath"
}

updateDb2PathVariables()
{
  logFnBegin "${FUNCNAME[0]}"
  DB2_LIB_PATH=$(extractDB2Lib64Path "$DB_ADMIN_USER")
  if [[ $DB2_LIB_PATH = "" ]]
  then
    writeMsg both "`nls_replace 'TEM0039E' \"DB2_LIB_PATH\" \"$DEF_BES_LOG_FILE\"`"
    exit 1
  fi
  logFnEnd "${FUNCNAME[0]}"
}

addResponseFileEntry()
{
  logFnBegin "${FUNCNAME[0]}"
  keyName=$1
  keyValue=$2
  writeMsg log "Response file entry: $keyName=$keyValue"
  ind=`echo ${#RESPONSE_KEY[*]}`
  # the arrays RESPONSE_KEY and RESPONSE_VAL work together like a map,
  # avoid inserting the same key more than once
  currInd=0
  for key in ${RESPONSE_KEY[*]}
  do
    if [ "$keyName" = "$key" ]
    then
      ind=$currInd
      break
    fi
    let currInd+=1
  done
  RESPONSE_KEY[$ind]=$keyName
  RESPONSE_VAL[$ind]=$keyValue
  logFnEnd "${FUNCNAME[0]}"
}

writeResponseFile()
{
  logFnBegin "${FUNCNAME[0]}"
  maxInd=`echo ${#RESPONSE_KEY[*]}`
  currInd=0
  while [[ $currInd -lt $maxInd ]]
  do
    echo "${RESPONSE_KEY[$currInd]}=\"${RESPONSE_VAL[$currInd]}\"" >> "$RESP_FILE_OUT"
    let currInd+=1
  done
  chmod 600 "$RESP_FILE_OUT"
  logFnEnd "${FUNCNAME[0]}"
}

addBesInfoFileEntry()
{
  logFnBegin "${FUNCNAME[0]}"
  keyName=$1
  keyValue=$2
  keyExists="false"
  for key in ${BES_KEY[*]}
  do
    [ "$keyName" = "$key" ] && keyExists="true"
  done
  if [[ $keyExists != "true" ]]
  then
    ind=`echo ${#BES_KEY[*]}`
    BES_KEY[$ind]=$keyName
    BES_VAL[$ind]=$keyValue
  fi
  logFnEnd "${FUNCNAME[0]}"
}

addOptEntry()
{
  logFnBegin "${FUNCNAME[0]}"
  optEntry=$1
  keyExists="false"
  keyName=$(echo "$optEntry"|while IFS='=' read tok1 tok2
  do
    echo "$(echo $tok1)"
  done)
  keyValue=$(echo "$optEntry"|while IFS='=' read tok1 tok2
  do
    echo "$(echo $tok2)"
  done)
  if [[ "$keyName" = "" || "$keyValue" = "" ]]
  then
    writeMsg both "`nls_replace 'TEM0130E' \"$optEntry\"`"
    Print_Usage
  fi
  for key in ${OPT_KEY[*]}
  do
    [ "$keyName" = "$key" ] && keyExists="true"
  done
  if [[ $keyExists != "true" ]]
  then
    ind=`echo ${#OPT_KEY[*]}`
    OPT_KEY[$ind]=$keyName
    OPT_VAL[$ind]=$keyValue
  fi
  logFnEnd "${FUNCNAME[0]}"
}

setOptEntry()
{
  logFnBegin "${FUNCNAME[0]}"
  maxInd=`echo ${#OPT_KEY[*]}`
  currInd=0
  while [[ $currInd -lt $maxInd ]]
  do
    opt="${OPT_KEY[$currInd]}=${OPT_VAL[$currInd]}"
    writeMsg log "The following input option has been specified: $opt"
    export "$opt"
    let currInd+=1
  done
  logFnEnd "${FUNCNAME[0]}"
}

writeBesInfoFile()
{
  logFnBegin "${FUNCNAME[0]}"
  destPath=$1

  if [[ $DB_TARGET = "db2" ]]
  then
    addBesInfoFileEntry "DB2_ADMIN_USER" "$DB_ADMIN_USER"
    addBesInfoFileEntry "DB2_INSTANCE" "$DB2_INSTANCE_NAME"
    addBesInfoFileEntry "DB2_LIB_PATH" "$DB2_LIB_PATH"
  fi

  maxInd=`echo ${#BES_KEY[*]}`
  currInd=0
  echo "##BES Info File (`eval date +%Y%m%d`)" > "$destPath$BES_INFO_FILE"
  while [[ $currInd -lt $maxInd ]]
  do
    echo "${BES_KEY[$currInd]}=${BES_VAL[$currInd]}" >> "$destPath$BES_INFO_FILE"
    let currInd+=1
  done
  chmod 644 "$destPath$BES_INFO_FILE"
  logFnEnd "${FUNCNAME[0]}"
}

writeMsg()
{
  dest=$1
  case $dest in
    stdout) echo "$2" >&2
            ;;
       log) echo "$2" >> $DEF_BES_LOG_FILE
            ;;
      both) echo "$2" >&2
            echo "$2" >> $DEF_BES_LOG_FILE
            ;;
  esac
}

extractFxfCharset()
{
  logFnBegin "${FUNCNAME[0]}"
  searchString="x-bes-fxf-charset"
  mastheadLine=""
  if [[ -f "$BES_MASTHEAD_FILE" ]]
  then
    mastheadLine=$(grep "$searchString" "$BES_MASTHEAD_FILE")
  fi
  # x-bes-fxf-charset: windows-1252
  charset=$(echo "$mastheadLine" | cut -d ' ' -f 2 | cut -d '-' -f 2)
  writeMsg log "Charset extracted from Masthead: $charset"
  logFnEnd "${FUNCNAME[0]}"
  echo "$charset"
}

extractServerUrlFromMasthead()
{
  logFnBegin "${FUNCNAME[0]}"
  searchString="X-Fixlet-Site-Registration-URL"
  mastheadLine=""
  if [[ -f "$BES_MASTHEAD_FILE" ]]
  then
    mastheadLine=$(grep "$searchString" "$BES_MASTHEAD_FILE")
  fi
  #Sample of line to parse
  #http://temtest03:52311/cgi-bin/bfenterprise/clientregister.exe
  #tok1="#http:" tok2="" tok3="temtest03:52311" tok4="cgi-bin/bfenterprise/clientregister.exe"
  serverUrl=$(echo "$mastheadLine"|while IFS='/' read tok1 tok2 tok3 tok4
  do
    echo "$tok3"
  done
  )
  writeMsg log "Server Url extracted from Masthead: $serverUrl"
  logFnEnd "${FUNCNAME[0]}"
  echo "$serverUrl"
}

getMastheadHostAndPort()
{
  logFnBegin "${FUNCNAME[0]}"
  MASTHEAD_URL=$(extractServerUrlFromMasthead)
  MASTHEAD_HOST=$(echo "$MASTHEAD_URL"|while IFS=':' read tok1 tok2
  do
    echo "$tok1"
  done)
  MASTHEAD_PORT=$(echo "$MASTHEAD_URL"|while IFS=':' read tok1 tok2
  do
    echo "$tok2"
  done)
  writeMsg log "MASTHEAD_HOST=$MASTHEAD_HOST , MASTHEAD_PORT=$MASTHEAD_PORT"
  logFnEnd "${FUNCNAME[0]}"
}

getRpmPkgName()
{
  logFnBegin "${FUNCNAME[0]}"
  rpmPrefix=$1
  rpmName=""
  pkgGrepCmd="grep ^$rpmPrefix.*.rpm"
  rpmNameCount=`ls "$DEF_BES_REPOS_FOLDER" | $pkgGrepCmd | wc -l`
  if [[ $rpmNameCount -gt 1 ]]
  then
    writeMsg both "`nls_replace 'TEM0099E' \"$rpmPrefix\" \"$DEF_BES_REPOS_FOLDER\"`"
  else
    rpmName=`ls "$DEF_BES_REPOS_FOLDER" | $pkgGrepCmd`
    if [[ $rpmName != "" ]]
    then
      if [[ $rpmPrefix = "$DEF_RPM_SRV_PREFIX" ]]
      then
        RPM_SRV_PKG=$rpmName
      elif [[ $rpmPrefix = "$DEF_RPM_WR_PREFIX" ]]
      then
        RPM_WR_PKG=$rpmName
      elif [[ $rpmPrefix = "$DEF_RPM_WEBUI_PREFIX" ]]
      then
        RPM_WEBUI_PKG=$rpmName
      else
        RPM_AGT_PKG=$rpmName
      fi
    else
      writeMsg both "`nls_replace 'TEM0036E' \"$rpmPrefix\" \"$DEF_BES_REPOS_FOLDER\"`"
    fi
  fi
  writeMsg log "Rpm Package Name: $rpmName"
  logFnEnd "${FUNCNAME[0]}"
}

isRpmInstalled()
{
  logFnBegin "${FUNCNAME[0]}"
  rpmPrefix=$1
  rpmArch=$2
  if [[  $rpmArch != "" ]]
  then
    rpmPrefix="$rpmPrefix.*$rpmArch"
  fi
  fnRc=0
  rpmList=`rpm -qa | grep $rpmPrefix`
  if [[ $rpmList != "" ]]
  then
    writeMsg log "`nls_replace 'TEM0061I' \"$rpmPrefix\"`"
    fnRc=1
  else
    fnRc=0
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

checkPrereqLib()
{
  logFnBegin "${FUNCNAME[0]}"
  libName=$1
  wrnMsg=$2
  libFound="false"
  rpmList=`rpm -qa | grep $libName`
  libFound=$(lineNum=0; echo "$rpmList" | while read line;
  do
    if [[ $line != "" ]]
    then
      let lineNum=lineNum+1
      writeMsg log "`nls_replace 'TEM0076I' \"$line\"`"
    fi
    if [[ $lineNum -eq 1 ]]
    then
      echo "true"
    fi
  done)
  if [[ $libFound != "true" ]]
  then
    echo $wrnMsg|while IFS=':' read msgKey msgVal
    do
      writeMsg log "`nls_replace $msgKey $msgVal`"
    done
    libFound="false"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$libFound"
}

checkRhelOs()
{
  logFnBegin "${FUNCNAME[0]}"
  osArch=`uname -m`
  prereqOk="false"
  if [[ -f /etc/redhat-release && $osArch = "x86_64" ]]
  then
    osDistr=`cat /etc/redhat-release`;
    writeMsg log "Info: OS Distribution $osDistr"
    prereqOk="true"
  else
    writeMsg log "Warning: OS Distribution or Architecture is not supported!"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$prereqOk"
}

checkStackSizeHardLimit()
{
  logFnBegin "${FUNCNAME[0]}"
  stackSizeHardLimitKB=`ulimit -Hs`
  prereqOk="false"
  if [[ "$stackSizeHardLimitKB" = "unlimited" || $stackSizeHardLimitKB -ge 10240 ]]
  then
    prereqOk="true"
  else
    writeMsg log "Warning: stack size hard limit ( ulimit -Hs ) is too low: $stackSizeHardLimitKB"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$prereqOk"
}

checkDB2Version()
{
  logFnBegin "${FUNCNAME[0]}"
  db2SearchStr="DB2 v"
  prereqOk="false"
  db2ExtVer=`su - $DB_ADMIN_USER  -c 'db2level | tr -d "\n" | tr "\"" "\n" | grep "^DB2 "'`;
  #DB2 v9.7.0.3
  prereqOk=$( echo "$db2ExtVer"|while IFS='v' read tokHead tokVer
  do
    db2HeaderMsg="DB2 Version"
    prereqOk=$(checkVersion $tokVer 10 1 "$db2HeaderMsg")
    echo "$prereqOk"
  done)
  logFnEnd "${FUNCNAME[0]}"
  echo "$prereqOk"
}

checkOsVersion()
{
  logFnBegin "${FUNCNAME[0]}"
  prereqOk="false"
  osExtVer=0
  if [[ -f /usr/bin/lsb_release ]]
  then
    osExtVer=`lsb_release -r -s`
  else
    osExtVer=$(getOsVersion)
  fi
  osHeaderMsg="OS Version"
  prereqOk=$(checkVersion $osExtVer 6 0 "$osHeaderMsg")
  logFnEnd "${FUNCNAME[0]}"
  echo "$prereqOk"
}

getOsVersion()
{
  logFnBegin "${FUNCNAME[0]}"
  osVer=0
  if [[ -f /etc/redhat-release ]]
  then
    osVer=$(grep -o '[0-9\.]*' /etc/redhat-release)
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo $osVer
}

checkVersion()
{
  logFnBegin "${FUNCNAME[0]}"
  ver=$1
  majVer=$2
  minVer=$3
  headerMsg=$4
  echo "$ver"|while IFS='.' read tok1 tok2 tok3
  do
    if [[ ($tok1 -gt $majVer) || ($tok1 -eq $majVer && $tok2 -ge $minVer) ]]
    then
      writeMsg log "Info: $headerMsg $ver"
      logFnEnd "${FUNCNAME[0]}"
      echo "true"
    else
      writeMsg log "Warning: $headerMsg '$ver' is not supported! Minimum supported version is: '$majVer.$minVer'"
      logFnEnd "${FUNCNAME[0]}"
      echo "false"
    fi
  done
}

# This function is called during both fresh install and upgrade.
# During the fresh install, it is called before choosing the components and so it requires all prerequisites.
checkOsPrereqs()
{
  logFnBegin "${FUNCNAME[0]}"
  PREREQ_OSRHEL_OK=$(checkRhelOs)
  if [[ $PREREQ_OSRHEL_OK = "true" ]]
  then
    PREREQ_OS_OK=$(checkOsVersion)
    PREREQ_STACKSIZELIMIT_OK=$(checkStackSizeHardLimit)
  fi

  if [[ $PREREQ_OSRHEL_OK = "false" || $PREREQ_OS_OK = "false" || $PREREQ_STACKSIZELIMIT_OK = "false" ]]
  then
    prerequisitesOsWarning
    if [[ $IGNORE_WARNING = "no" ]]
    then
      writeMsg both "`nls_replace 'TEM0001W'`"
      exit 1
    fi
  fi

  if [[ $PREREQ_OS_OK = "true" ]]
  then
    wrnCnt=0
    pkgNameSearch=("^cyrus-sasl-lib.*x86_64" "^libstdc++.*x86_64" "^pam.*x86_64" "^krb5-libs.*x86_64")
    pkgNameInst=("cyrus-sasl-lib" "libstdc++" "pam" "krb5-libs")
    pkgWrnMsg=(
      "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64"
      "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64"
      "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64"
      "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64")
    pkgEnvVar=("_" "_" "_" "_")

    if [[ $BES_UPGRADE = "false" ]]
    then
      pkgNameSearch=(${pkgNameSearch[*]} "^net-tools.*x86_64")
      pkgNameInst=(${pkgNameInst[*]} "net-tools")
      pkgWrnMsg=(${pkgWrnMsg[*]}
        "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64")
      pkgEnvVar=(${pkgEnvVar[*]} "_")
    fi

    if [[ $BES_UPGRADE = "false" || $COMPONENT_WR = "true" ]]
    then
      pkgNameSearch=(${pkgNameSearch[*]} "^fontconfig.*x86_64" "^libXext.*x86_64" "^libXrender.*x86_64" "^zlib.*x86_64")
      pkgNameInst=(${pkgNameInst[*]} "fontconfig" "libXext" "libXrender" "zlib")
      pkgWrnMsg=(${pkgWrnMsg[*]}
        "TEM0078W:${pkgNameInst[$((wrnCnt++))]}.x86_64"
        "TEM0078W:${pkgNameInst[$((wrnCnt++))]}.x86_64"
        "TEM0078W:${pkgNameInst[$((wrnCnt++))]}.x86_64"
        "TEM0078W:${pkgNameInst[$((wrnCnt++))]}.x86_64")
      pkgEnvVar=(${pkgEnvVar[*]} "_" "_" "_" "_")
      osVer=$(getOsVersion)
      if [[ $osVer != 6* ]]
      then
        pkgNameSearch=(${pkgNameSearch[*]} "^libpng12.*x86_64")
        pkgNameInst=(${pkgNameInst[*]} "libpng12")
        pkgWrnMsg=(${pkgWrnMsg[*]} "TEM0078W:${pkgNameInst[$((wrnCnt++))]}.x86_64")
        pkgEnvVar=(${pkgEnvVar[*]} "_")
      fi
    fi

    if [[ $BES_UPGRADE = "false" || $COMPONENT_SRV = "true" || $COMPONENT_WR = "true" ]] 
    then
      if [[ $DB_TARGET = "db2" ]]
      then
        pkgNameSearch=(${pkgNameSearch[*]} "^unixODBC.*x86_64")
        pkgNameInst=(${pkgNameInst[*]} "unixODBC")
        pkgWrnMsg=(${pkgWrnMsg[*]}
          "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64")
        pkgEnvVar=(${pkgEnvVar[*]} "_")
      else
        # TODO We should check if Microsoft repository is enabled (https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15#redhat17)
        pkgNameSearch=(${pkgNameSearch[*]} "^msodbcsql17.*x86_64")
        pkgNameInst=(${pkgNameInst[*]} "msodbcsql17")
        pkgWrnMsg=(${pkgWrnMsg[*]}
          "TEM0077W:${pkgNameInst[$((wrnCnt++))]}.x86_64")
        pkgEnvVar=(${pkgEnvVar[*]} "ACCEPT_EULA=Y")
      fi
    fi

    pkgExt=("x86_64")

    pkgIsInstalled=()
    i=0
    for pkgName in ${pkgNameSearch[*]}
    do
      pkgIsInstalled[i]=$(checkPrereqLib "$pkgName" ${pkgWrnMsg[i]})
      let i=i+1
    done

    wrnList=()
    j=0
    k=0
    for pkg in ${pkgIsInstalled[*]}
    do
      if [[ $pkg = "false" ]]
      then
        wrnList[j]=${pkgWrnMsg[k]}
        let j=j+1
      fi
      let k=k+1
    done

    for isInst in ${pkgIsInstalled[*]}
    do
      if [[ "$isInst" != "true" ]]
      then
        ##Overwrite BES_PREREQ_INSTALL variable in case of prereq check
        [[ $IS_PREREQ_CHECK = "true" ]] && BES_PREREQ_INSTALL="install"
        selectPackageInstall "${wrnList[*]}"
        case $BES_PREREQ_INSTALL in
          exit) ##Exit from installation
             writeMsg both "`nls_replace 'TEM0001W'`"
             exit 1
             ;;
          install) ##Continue, installing prereq
             yumInstallPkgs "${pkgNameInst[*]}" "${pkgIsInstalled[*]}" "${pkgExt[*]}" "${pkgEnvVar[*]}"
             ;;
          ##Otherwise Continue, ignore Warning
        esac
        break
      fi
    done
  fi

  if [[ $IS_PREREQ_CHECK = "true" ]]
  then
    writeMsg both "`nls_replace 'TEM0131I'`"
    exit 0
  fi
  logFnEnd "${FUNCNAME[0]}"
}

checkDB2OsPrereqs()
{
  logFnBegin "${FUNCNAME[0]}"
  pkgNameSearch=("^numactl.*x86_64" "^pam.*i686" "^libstdc++.*i686" "^binutils.*x86_64")
  pkgNameInst=("numactl" "pam" "libstdc++" "binutils")
  pkgWrnMsg=("TEM0079W:${pkgNameInst[0]}.x86_64" "TEM0079W:${pkgNameInst[1]}.i686" "TEM0079W:${pkgNameInst[2]}.i686" "TEM0079W:${pkgNameInst[3]}.x86_64")
  pkgEnvVar=("_" "_" "_" "_")

  pkgExt=("x86_64" "i686")

  pkgIsInstalled=()
  i=0
  for pkgName in ${pkgNameSearch[*]}
  do
    pkgIsInstalled[i]=$(checkPrereqLib "$pkgName" ${pkgWrnMsg[i]})
    let i=i+1
  done

  wrnList=()
  j=0
  k=0
  for pkg in ${pkgIsInstalled[*]}
  do
    if [[ $pkg = "false" ]]
    then
      wrnList[j]=${pkgWrnMsg[k]}
      let j=j+1
    fi
    let k=k+1
  done

  for isInst in ${pkgIsInstalled[*]}
  do
    if [[ "$isInst" != "true"  ]]
    then
      selectDB2PackageInstall "${wrnList[*]}"
      case $BES_PREREQ_DB2_INSTALL in
        exit) ##Exit from installation
           writeMsg both "`nls_replace 'TEM0001W'`"
           exit 1
           ;;
        install) ##Continue, installing prereq
           yumInstallPkgs "${pkgNameInst[*]}" "${pkgIsInstalled[*]}" "${pkgExt[*]}" "${pkgEnvVar[*]}" "${pkgNameSearch[*]}"
           ;;
        ##Otherwise Continue, ignore Warning
      esac
      break
    fi
  done
  logFnEnd "${FUNCNAME[0]}"
}

yumInstallPkgs()
{
  logFnBegin "${FUNCNAME[0]}"
  pkgName=($1)
  pkgIsInstalled=($2)
  pkgExt=($3)
  # use '_' for any package that does not require any environment variables for its installation
  pkgEnvVar=($4)
  pkgSearch=($5)
  i=0
  for pkg in ${pkgName[*]}
  do
    if [[ "${pkgIsInstalled[i]}" = "false" ]]
    then
      for ext in ${pkgExt[*]}
      do
        yumCmd="yum -y install $pkg.$ext"
        envVar="${pkgEnvVar[i]}"
        if [[ "$envVar" != "_" ]]; then
          yumCmd="env $envVar $yumCmd"
        fi
        writeMsg log "$yumCmd"
        writeMsg both "`nls_replace 'TEM0124I' \"$pkg.$ext\"`"
        $yumCmd >> $DEF_BES_LOG_FILE 2>> $DEF_BES_LOG_FILE
        if [[ $? -ne 0 ]]
        then
          pkgPattern=${pkgSearch[i]}
          # When checking if the package is installed we look for a specific
          # extension but here we try to install every extension that is passed
          # in. So consider an error only if the extension we fail to install
          # was actually the one we searched in the first place.
          if [[ -z $pkgPattern || $pkgPattern = *$ext ]]
          then
            writeMsg both "`nls_replace 'TEM0123E' \"$DEF_BES_LOG_FILE\"`"
            exit 1
          fi
        fi
      done
    fi
    let i=i+1
  done
  logFnEnd "${FUNCNAME[0]}"
}

unsetInstalledComponents()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $COMPONENT_SRV = "true" ]]
  then
    isRpmInstalled "$DEF_RPM_SRV_PREFIX"
    lastrc=$?
    if [[ $lastrc -ne 0 ]]
    then
      COMPONENT_SRV="false"
      writeMsg both "`nls_replace 'TEM0035W'`"
    else
      installRc=0
      compList=($DEF_RPM_AGT_PREFIX $DEF_RPM_REL_PREFIX)
      for comp in ${compList[*]}
      do
        isRpmInstalled "$comp"
        let "installRc=installRc+$?"
      done
      if [[ $installRc -ne 0 ]]
      then
        writeMsg both "`nls_replace 'TEM0060E' \"$DEF_BES_LOG_FILE\"`"
        exit 1
      fi
    fi
  fi
  if [[ $COMPONENT_WR = "true" ]]
  then
    isRpmInstalled "$DEF_RPM_WR_PREFIX"
    lastrc=$?
    if [[ $lastrc -ne 0 ]]
    then
      COMPONENT_WR="false"
      writeMsg both "`nls_replace 'TEM0089W'`"
    fi
  fi 
  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    isRpmInstalled "$DEF_RPM_WEBUI_PREFIX"
    lastrc=$?
    if [[ $lastrc -ne 0 ]]
    then
      COMPONENT_WEBUI="false"
      writeMsg both "`nls_replace 'TEM0175W'`"
    fi
  fi
  if [[ $COMPONENT_SRV = "false" && $COMPONENT_WR = "false" && $COMPONENT_WEBUI = "false" ]]
  then
     writeMsg both "`nls_replace 'TEM0034I'`"
     exit 0
  fi
  logFnEnd "${FUNCNAME[0]}"
}

checkAllCompsInstalled()
{
  logFnBegin "${FUNCNAME[0]}"
  compList=($DEF_RPM_SRV_PREFIX $DEF_RPM_WR_PREFIX $DEF_RPM_WEBUI_PREFIX)
  allInstalled=$(for comp in ${compList[*]}
    do
      isRpmInstalled "$comp"
      if [[ $? -eq 0 ]]
      then
        isInstalled="false"
      fi
    done
    [[ $isInstalled = "false" ]] && echo "false" || echo "true"
  )
  if [[ $allInstalled = "true" ]]
  then
    writeMsg both "`nls_replace 'TEM0133I'`"
    writeMsg both "`nls_replace 'TEM0134W'`"
    exit 1
  fi
  logFnEnd "${FUNCNAME[0]}"
}

checkCleanEnv()
{
  logFnBegin "${FUNCNAME[0]}"
  isClean="true"
  compList=($DEF_RPM_SRV_PREFIX $DEF_RPM_WR_PREFIX $DEF_RPM_AGT_PREFIX $DEF_RPM_REL_PREFIX $DEF_RPM_WEBUI_PREFIX)
  isClean=$(for comp in ${compList[*]}
    do
      isRpmInstalled "$comp"
      if [[ $? -ne 0 ]]
      then
        isClean="false"
      fi
    done
    echo "$isClean"
  )
  if [[ $isClean = "false" ]]
  then
    writeMsg both "`nls_replace 'TEM0062E' \"$DEF_BES_LOG_FILE\"`"
    exit 1
  fi
  logFnEnd "${FUNCNAME[0]}"
}

identifyInstalledComps()
{
  logFnBegin "${FUNCNAME[0]}"
  isRpmInstalled "$DEF_RPM_SRV_PREFIX"
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
     COMPONENT_SRV="true"
  fi
  isRpmInstalled "$DEF_RPM_WR_PREFIX"
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
     COMPONENT_WR="true"
  fi
  isRpmInstalled "$DEF_RPM_WEBUI_PREFIX"
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
    COMPONENT_WEBUI="true"
  fi
  logFnEnd "${FUNCNAME[0]}"
}

daemonReload()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ -f "/usr/bin/systemctl" ]]
  then
    `/usr/bin/systemctl daemon-reload`
  fi
  logFnEnd "${FUNCNAME[0]}"
}

startService()
{
  logFnBegin "${FUNCNAME[0]}"
  inputService=($1)
  serviceName=${inputService[0]}
  serviceProc=${inputService[1]}
  lastrc=1
  fnRc=0
  ##verify if the service has been created by the rpm
  if [[ -f /etc/init.d/$serviceName ]]
  then
    service $serviceName start > /dev/null
    lastrc=$?
  fi
  if [[ $lastrc -ne 0 ]]
  then
    ##The start service returns an error
    writeMsg both "`nls_replace 'TEM0014E' \"$serviceProc\"`"
  else
    ##wait few seconds before checking for the service status
    sleep 5
    service $serviceName status >> $DEF_BES_LOG_FILE
    lastrc=$?
    ##The status command returns:
    ##    0 if the service is running
    ##    not 0 in all the other cases
    if [[ $lastrc -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0015E' \"$serviceProc\"`"
    else
      writeMsg both "`nls_replace 'TEM0016I' \"$serviceProc\"`"
    fi
  fi
  if [[ $lastrc -ne 0 ]]
  then
    fnRc=1
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

stopService()
{
  logFnBegin "${FUNCNAME[0]}"
  inputService=($1)
  serviceName=${inputService[0]}
  serviceProc=${inputService[1]}
  lastrc=1
  if [[ -f /etc/init.d/$serviceName ]]
  then
    service $serviceName stop > /dev/null
    lastrc=$?
  fi
  if [[ $lastrc -ne 0 ]]
  then
    ##The stop service returns an error
    writeMsg log "`nls_replace 'TEM0068W' \"$serviceProc\"`"
  fi
  logFnEnd "${FUNCNAME[0]}"
}

copyFolderContent()
{
  logFnBegin "${FUNCNAME[0]}"
  source=$1
  dest=$2
  subdir=$3
  fnRc=0
  if [[ $source != $dest ]]
  then
    \cp -Rf "$source"/* "$dest" 2>> $DEF_BES_LOG_FILE
    lastrc=$?
    if [[ $lastrc -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0017E' \"$source\" \"$dest\"`"
      fnRc=1
    else
      writeMsg both "`nls_replace 'TEM0086I' \"$dest\"`"
      if [[ $source = *$subdir* ]]
      then 
        \rm -Rf "$source"
      fi
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

moveFolders()
{
  logFnBegin "${FUNCNAME[0]}"
  source=$1
  dest=$2
  subdir=$3
  fnRc=0
  if [[ $source != $dest ]]
  then
    mv -f "$source$subdir" "$dest$subdir" 2>> $DEF_BES_LOG_FILE
    lastrc=$?
    ##The move command returns:
    ##    0 if the move directory is success
    ##    not 0 in case of failure
    if [[ $lastrc -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0017E' \"$source\" \"$dest\"`"
      fnRc=1
    else
      writeMsg both "`nls_replace 'TEM0018I' \"$dest$subdir\"`"
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

renameAuthFile()
{
  logFnBegin "${FUNCNAME[0]}"
  fnRc=0
  usedAuthFile="$BES_AUTH_FILE.used_"`eval date +%Y%m%d`

  mv -f "$BES_AUTH_FILE" "$usedAuthFile" 2>> $DEF_BES_LOG_FILE
  lastrc=$?
  if [[ $lastrc -eq 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0125I' \"$usedAuthFile\"`"
    if [[ $SUBMIT_LIC_REQUEST = "yes" ]]
    then
      writeMsg both "`nls_replace 'TEM0126I' \"$BES_LIC_FOLDER$DEF_BES_CERT_FILE\" \"$BES_LIC_FOLDER$DEF_BES_LICENSE_PVK\"`"
    else
      writeMsg both "`nls_replace 'TEM0127I' \"$BES_LIC_FOLDER$DEF_BES_REQUEST\"`"
    fi
    sleep 3
  fi
  logFnEnd "${FUNCNAME[0]}"
}

addReplicationParms()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1
  echo "[Software\BigFix\Enterprise Server\FillDB]" >> $configFile
  echo "ReplicationDatabase               = <BES_DB_NAME>" >> $configFile
  echo "ReplicationUser                   = <DB2_MASTER_USER>" >> $configFile
  echo "ReplicationPassword               = <DB2_MASTER_PWD>" >> $configFile
  echo "ReplicationPort                   = <DB2_MASTER_PORT>" >> $configFile
  logFnEnd "${FUNCNAME[0]}"
}

addWebUIRedirectPort()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1
  echo "[Software\BigFix\EnterpriseClient\Settings\Client\_WebUI_Redirect_Port]" >> $configFile
  echo "value                          = <WEBUI_REDIRECT_PORT>" >> $configFile
  logFnEnd "${FUNCNAME[0]}"
}

addWRDataSourceParms()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1
  echo "[SOFTWARE\BigFix\Enterprise Server\FillAggregateDB\RemoteDatabases\<ENCODED_DATASOURCE_NAME>]" >> $configFile
  if [[ $LOCAL_DATABASE = "false" ]]
  then
    echo "Name                           = <DB_HOSTNAME>" >> $configFile
    driver=""
    if [[ $DB_TARGET = "db2" ]]
    then
      driver="{IBM DB2 ODBC Driver-DB2COPY1}"
    else
      driver="SQL Server"
    fi
    echo "DSNName                        = Driver=$driver;Server=<DB_HOSTNAME>;Database=<BES_DB_NAME>;Port=<DB_PORT>;" >> $configFile
  else
    echo "Name                           = <DATASOURCE_NAME>" >> $configFile
    echo "DSNName                        = Server=<DB_HOSTNAME>;Database=<BES_DB_NAME>;" >> $configFile
  fi
  echo "Username                       = <DB_CONN_USER>" >> $configFile
  echo "Password                       = <DB_CONN_PWD>" >> $configFile
  echo "TrustedConnection              = 1" >> $configFile
  echo "WebReportsURL                  = http://<SRV_DNS_NAME>:<WR_WWW_PORT>/webreports" >> $configFile
  logFnEnd "${FUNCNAME[0]}"
}

createPasswordFile()
{
  logFnBegin "${FUNCNAME[0]}"
  pswdFile=$1
  section=$2
  value=$3
  echo "[$section]" >> $pswdFile
  echo "value = $value" >> $pswdFile
  echo "" >> $pswdFile
  logFnEnd "${FUNCNAME[0]}"
}

updateConfigFile()
{
  logFnBegin "${FUNCNAME[0]}"
  inputFile=$1
  outputFile=$2
  lastrc=1
  fnRc=0
  besWWWFolder="$BES_WWW_FOLDER$DEF_BES_WWW_FOLDER"
  if [[ -f $inputFile ]]
  then
    if [[ $LOCAL_DATABASE = "false" ]]
    then
       DB_HOSTNAME_RES="$DB_HOSTNAME"
	   USE_REMOTE_DB=1
    else
       DB_HOSTNAME_RES="localhost"
	   USE_REMOTE_DB=0
    fi
    cpuNumber=`cat /proc/cpuinfo | grep -c processor`
    if [[ cpuNumber -ge 10 ]]
    then
        PARALLELISM_ENABLED="1"
        PARALLELISM_ENABLED_FOR_QUERY="1"
    elif [[ cpuNumber -ge 6 ]]
    then
        PARALLELISM_ENABLED="1"
        PARALLELISM_ENABLED_FOR_QUERY="0"
    else
        PARALLELISM_ENABLED="0"
        PARALLELISM_ENABLED_FOR_QUERY="0"
    fi

    awk -v search1="<BES_WWW_FOLDER>" -v replace1="$besWWWFolder" -v search2="<DB_HOSTNAME>" -v replace2="$DB_HOSTNAME_RES" -v search3="<DB_CONN_USER>" -v replace3="$DB_CONN_USER" -v search4="<DB_CONN_PWD>" -v replace4="\"\"" -v search5="<BES_DB_NAME>" -v replace5="$BES_DB_NAME" -v search6="<DB_PORT>" -v replace6="$DB_PORT" -v search7="<DB2_MASTER_USER>" -v replace7="$DB2_MASTER_USER" -v search8="<DB2_MASTER_PWD>" -v replace8="\"\"" -v search9="<BES_SERVER_PORT>" -v replace9="$BES_SERVER_PORT" -v search10="<SRV_DNS_NAME>" -v replace10="$SRV_DNS_NAME" -v search11="<ENCODE_VALUE>" -v replace11="$ENCODE_VALUE" -v search12="<DB2_MASTER_PORT>" -v replace12="$DB2_MASTER_PORT" -v search13="<PARALLELISM_ENABLED>" -v replace13="$PARALLELISM_ENABLED" -v search14="<PARALLELISM_ENABLED_FOR_QUERY>" -v replace14="$PARALLELISM_ENABLED_FOR_QUERY" -v search15="<USE_REMOTE_DB>" -v replace15="$USE_REMOTE_DB" '{
      gsub(search1,replace1)
      gsub(search2,replace2)
      gsub(search3,replace3)
      gsub(search4,replace4)
      gsub(search5,replace5)
      gsub(search6,replace6)
      gsub(search7,replace7)
      gsub(search8,replace8)
      gsub(search9,replace9)
      gsub(search10,replace10)
      gsub(search11,replace11)
      gsub(search12,replace12)
      gsub(search13,replace13)
      gsub(search14,replace14)
      gsub(search15,replace15)
      print
     }' $inputFile > $outputFile
     lastrc=$?
  else
    writeMsg both "`nls_replace 'TEM0019E' \"$inputFile\"`"
  fi
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0020E' \"$outputFile\"`"
    fnRc=1
  else
    writeMsg log "`nls_replace 'TEM0021I' \"$outputFile\"`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

updateWrConfigFile()
{
  logFnBegin "${FUNCNAME[0]}"
  inputFile=$1
  outputFile=$2
  lastrc=1
  fnRc=0
  wrWWWFolder="$WR_WWW_FOLDER$DEF_WR_WWW_FOLDER"
  if [[ -f $inputFile ]]
  then
    if [[ $LOCAL_DATABASE = "false" ]]
    then
       DB_HOSTNAME_RES="$DB_HOSTNAME"
	   USE_REMOTE_DB=1
    else
       DB_HOSTNAME_RES="localhost"
	   USE_REMOTE_DB=0
    fi
	DB_HOSTNAME_ENC=$(echo "$DB_HOSTNAME" | sed -r 's/\./%2e/g')
    awk -v search1="<WR_WWW_FOLDER>" -v replace1="$wrWWWFolder" -v search2="<DB_HOSTNAME>" -v replace2="$DB_HOSTNAME_RES" -v search3="<DB_CONN_USER>" -v replace3="$DB_CONN_USER" -v search4="<DB_CONN_PWD>" -v replace4="\"\"" -v search5="<DB_PORT>" -v replace5="$DB_PORT" -v search6="<SRV_DNS_NAME>" -v replace6="$SRV_DNS_NAME" -v search7="<WR_WWW_PORT>" -v replace7="$WR_WWW_PORT" -v search8="<ENCODE_VALUE>" -v replace8="$ENCODE_VALUE" -v search9="<DATASOURCE_NAME>" -v replace9="$DB_HOSTNAME" -v search10="<BES_DB_NAME>" -v replace10="$BES_DB_NAME" -v search11="<WR_DB_NAME>" -v replace11="$WR_DB_NAME" -v search12="<ENCODED_DATASOURCE_NAME>" -v replace12="$DB_HOSTNAME_ENC" -v search13="<WR_PEM>" -v replace13="$DEF_WR_PEM" -v search14="<USE_REMOTE_DB>" -v replace14="$USE_REMOTE_DB" '{
      gsub(search1,replace1)
      gsub(search2,replace2)
      gsub(search3,replace3)
      gsub(search4,replace4)
      gsub(search5,replace5)
      gsub(search6,replace6)
      gsub(search7,replace7)
      gsub(search8,replace8)
      gsub(search9,replace9)
      gsub(search10,replace10)
      gsub(search11,replace11)
      gsub(search12,replace12)
      gsub(search13,replace13)
      gsub(search14,replace14)
      print
     }' $inputFile > $outputFile
     lastrc=$?
  else
    writeMsg both "`nls_replace 'TEM0019E' \"$inputFile\"`"
  fi
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0020E' \"$outputFile\"`"
    fnRc=1
  else
    writeMsg log "`nls_replace 'TEM0021I' \"$outputFile\"`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

# This is mainly due to the way we chose to install the WebUI. We are leveraging the client
# config file instead of the beswebui.config file
updateClientConfigFile()
{
  logFnBegin "${FUNCNAME[0]}"
  serverHost=$SRV_DNS_NAME
  if [[ $COMPONENT_SRV = "false" && $COMPONENT_WR = "true" ]]
  then
    serverHost=$MASTHEAD_HOST
  fi

  clientConfigFile="$DEF_CLIENT_CONFIG_DEFAULT"
  if [ -f $DEF_CLIENT_CONFIG ]
  then
    clientConfigFile="$DEF_CLIENT_CONFIG"
  fi

  updateClientSetting $clientConfigFile "_WebUI_HTTPS_Port" "$WEBUI_PORT"
  updateClientSetting $clientConfigFile "_WebUI_Redirect_Enable" "$DEF_WEBUI_REDIRECT_ENABLE"
  updateClientSetting $clientConfigFile "_WebUI_Redirect_Port" "$WEBUI_REDIRECT_PORT"
  updateClientSetting $clientConfigFile "_WebUIAppEnv_PLATFORM_HOST" "$SRV_DNS_NAME"
  updateClientSetting $clientConfigFile "_WebUIAppEnv_USE_BFENT" "1"
  updateClientSetting $clientConfigFile "_WebUIAppEnv_WebUI_DIR" "$DEF_WEBUI_ROOT"
  updateClientSetting $clientConfigFile "_WebUIAppEnv_WORK_DIR" "$DEF_WEBUI_SITES_DIR"

  writeUpdConfigFile $clientConfigFile

  writeMsg log "`nls_replace 'TEM0181I' \"$clientConfigFile\"`"
  logFnEnd "${FUNCNAME[0]}"
}

configureDB2RespFile()
{
  logFnBegin "${FUNCNAME[0]}"
  inputFile=$1
  outputFile=$2
  lastrc=1
  fnRc=0
  if [[ -f $inputFile ]]
  then
    awk -v search1="<DB2_INSTALL_DIR>" -v replace1="$DB2_INSTALL_DIR" -v search2="<DB2_INSTANCE_NAME>" -v replace2="$DB2_INSTANCE_NAME" -v search3="<DB2_FENCED_USERNAME>" -v replace3="$DB2_FENCED_USERNAME" -v search4="<DB2_PORT>" -v replace4="$DB_PORT" -v search5="<DB2_USERS_PWD>" -v replace5="$DB2_USERS_PWD" -v search6="<DB2_PORT>" -v replace6="$DB_PORT" '{
      gsub(search1,replace1)
      gsub(search2,replace2)
      gsub(search3,replace3)
      gsub(search4,replace4)
      gsub(search5,replace5)
      gsub(search6,replace6)
      print
    }' $inputFile > $outputFile
    lastrc=$?
    [[ -f $outputFile ]] && chmod 600 $outputFile
  else
    writeMsg both "`nls_replace 'TEM0019E' \"$inputFile\"`"
  fi
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0020E' \"$outputFile\"`"
    fnRc=1
  else
    writeMsg log "`nls_replace 'TEM0021I' \"$outputFile\"`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

resolveScriptTag()
{
  logFnBegin "${FUNCNAME[0]}"
  fromStr=$1
  toStr=$2
  inputFile=$3
  outputFile=$4
  isSameFile="false"
  if [[ $outputFile = "" ]]
  then
    isSameFile="true"
    outputFile="$inputFile"_bkp
  fi
  lastrc=1
  fnRc=0
  if [[ -f $inputFile ]]
  then
    awk -v search="$fromStr" -v replace="$toStr" '{
      gsub(search,replace)
      print
     }' $inputFile > $outputFile
    lastrc=$?
  else
    writeMsg both "`nls_replace 'TEM0019E' \"$inputFile\"`"
  fi
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0020E' \"$outputFile\"`"
    fnRc=1
  else
    chmod 755 $outputFile
    writeMsg log "`nls_replace 'TEM0021I' \"$outputFile\"`"
    if [[ $isSameFile = "true" ]]
    then
      mv -f $outputFile $inputFile
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

removeLineFromFile()
{
  logFnBegin "${FUNCNAME[0]}"
  line="$1"
  file="$2"
  sed -i "/$line/d" "$file"
  lastrc=$?
  logFnEnd "${FUNCNAME[0]}"
  return $lastrc
}

installRpm()
{
  logFnBegin "${FUNCNAME[0]}"
  rpmPrefix=$1
  installOpt=$2
  rpmName=""
  rpmFile=""
  rpmCmd="rpm -i"
  getRpmPkgName $rpmPrefix
  if [[ $rpmPrefix = "$DEF_RPM_SRV_PREFIX" ]]
  then
    [[ "$RPM_SRV_PKG" = "" ]] || rpmName="$RPM_SRV_PKG"
  elif [[ $rpmPrefix = "$DEF_RPM_WR_PREFIX" ]]
  then
    [[ "$RPM_WR_PKG" = "" ]] || rpmName="$RPM_WR_PKG"
  elif [[ $rpmPrefix = "$DEF_RPM_WEBUI_PREFIX" ]]
  then
    [[ "$RPM_WEBUI_PKG" = "" ]] || rpmName="$RPM_WEBUI_PKG"
  else
    [[ "$RPM_AGT_PKG" = "" ]] || rpmName="$RPM_AGT_PKG"
  fi
  [[ "$rpmName" = "" ]] || rpmFile="$DEF_BES_REPOS_FOLDER/$rpmName"
  #Rpm Package not found
  [ "$rpmFile" ] || checkFatalerror "1"

  rpmPackageName=${rpmName%.*}
  isRpmInstalled "$rpmPackageName" 
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg log "Package $rpmPackageName is already installed"
    logFnEnd "${FUNCNAME[0]}"
    return 0
  fi
  fnRc=0
  if [[ $installOpt = "-upgrade" ]]
  then
    rpmCmd="rpm -U"
  fi
  if [[ -f $rpmFile ]]
  then
    $rpmCmd $rpmFile 2>> $DEF_BES_LOG_FILE 
    lastrc=$?
    if [[ $lastrc -ne 0 ]] 
    then
      writeMsg both "`nls_replace 'TEM0025E' \"$rpmFile\"`"
      fnRc=1
    else
      writeMsg both "`nls_replace 'TEM0026I' \"$rpmFile\"`"
    fi
  else
    writeMsg log "`nls_replace 'TEM0024E' \"$rpmFile$rpmPrefix\"`"
    fnRc=1
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

upgradeRpm()
{
  logFnBegin "${FUNCNAME[0]}"
  rpmUpgPrefix=$1
  rpmName=""
  isUpgrade="true"
  getRpmPkgName $rpmUpgPrefix
  if [[ $rpmUpgPrefix = "$DEF_RPM_SRV_PREFIX" ]]
  then
    [[ "$RPM_SRV_PKG" = "" ]] || rpmName="$RPM_SRV_PKG"
  elif [[ $rpmUpgPrefix = "$DEF_RPM_WR_PREFIX" ]]
  then
    [[ "$RPM_WR_PKG" = "" ]] || rpmName="$RPM_WR_PKG"
  elif [[ $rpmUpgPrefix = "$DEF_RPM_WEBUI_PREFIX" ]]
  then
    [[ "$RPM_WEBUI_PKG" = "" ]] || rpmName="$RPM_WEBUI_PKG"
  else
    [[ "$RPM_AGT_PKG" = "" ]] || rpmName="$RPM_AGT_PKG"
  fi
  isRpmInstalled "$rpmUpgPrefix" "x86_64"
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
    rpmPackageName=${rpmName%.*}
    isRpmInstalled "$rpmPackageName"
    lastrc=$?
    if [[ $lastrc -ne 0 ]]
    then
      writeMsg log "Package $rpmPackageName is already installed"
      logFnEnd "${FUNCNAME[0]}"
      return 0
    fi
  else
    isRpmInstalled "$rpmUpgPrefix" "i686"
    lastrc=$?
    if [[ $lastrc -ne 0 ]]
    then
      rpm32List=`rpm -qa | grep $rpmUpgPrefix | grep BES`
      rpmRmCmd="rpm -e $rpm32List --noscripts"
      writeMsg log "Running $rpmRmCmd"
      $rpmRmCmd 2>> $DEF_BES_LOG_FILE
      isUpgrade="false"
    fi
  fi
  if [[ $isUpgrade = "true" ]]
  then
    installRpm "$rpmUpgPrefix" "-upgrade"
    fnRc=$?
  else
    installRpm "$rpmUpgPrefix"
    fnRc=$?
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

updateMasthead()
{
  logFnBegin "${FUNCNAME[0]}"
  updMasthead="false"
  serverVersion=`rpm -qi $DEF_RPM_SRV_PREFIX | grep Version | awk '{print $3}'`

  # If current version is less than 10.0.7 the mashead must be updated
  if [ "$(printf '%s\n' "10.0.7" "${serverVersion}" | sort -V | head -n1)" = "${serverVersion}" ]; then
      updMasthead="true"
  fi

  logFnEnd "${FUNCNAME[0]}"
  echo "$updMasthead"
}

installDB2()
{
  logFnBegin "${FUNCNAME[0]}"
  db2setup=$1
  db2rsp=$2
  lastrc=0
  fnRc=0
  writeMsg both "`nls_replace 'TEM0118I'`"
  if [[ -f $db2rsp ]]
  then
    "$db2setup" -r "$db2rsp" >> $DEF_BES_LOG_FILE 2>> $DEF_BES_LOG_FILE
    lastrc=$?
    \rm -f "$db2rsp"
    if [[ $lastrc -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0116E'`"
      fnRc=1
    else
      writeMsg both "`nls_replace 'TEM0115I'`"
    fi
  else
    writeMsg both "`nls_replace 'TEM0024E' \"$db2rsp\"`"
    fnRc=1
  fi

  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

verifyDB2Install()
{
  logFnBegin "${FUNCNAME[0]}"
  db2ValPath=$1
  db2ValFile="/db2val"
  db2CmdLogPath="/tmp/db2val-yymmdd_hhmmss.log"
  lastrc=0
  fnRc=0
  writeMsg both "`nls_replace 'TEM0119I' \"$db2ValPath\"`"
  if [[ -f $db2ValPath$db2ValFile ]]
  then

    #db2val only works if locale is en_US
    LANGUAGE_COPY=$LANGUAGE
    LANG_COPY=$LANG
    LC_ALL_COPY=$LC_ALL
    LANGUAGE=en_US.UTF8
    LANG=en_US.UTF8
    LC_ALL=en_US.UTF8

    "$db2ValPath$db2ValFile" >> $DEF_BES_LOG_FILE 2>> $DEF_BES_LOG_FILE
    lastrc=$?

    LANGUAGE=$LANGUAGE_COPY
    LANG=$LANG_COPY
    LC_ALL=$LC_ALL_COPY

    if [[ $lastrc -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0120E' \"$db2CmdLogPath\"`"
      fnRc=1
    else
      writeMsg both "`nls_replace 'TEM0121I'`"
    fi
  else
    writeMsg both "`nls_replace 'TEM0024E' \"$db2cmd\"`"
    fnRc=1
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

copyDB2LicenseDir()
{
  logFnBegin "${FUNCNAME[0]}"
  lastrc=0
  fnRc=0
  srcLicenseDir="$DB2_SRC_LIC_FOLDER"
  dstLicenseDir="$DB2_INSTALL_DIR/$DB2_DST_LIC_FOLDER_NAME"
  if [[ ! -d "$srcLicenseDir" ]]
  then
    writeMsg both "`nls_replace 'TEM0108W' \"$srcLicenseDir\"`"
  else
    \cp -rf "$srcLicenseDir" "$dstLicenseDir"
    fnRc=1
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

setRegistryValuesForDb2Locking()
{
  logFnBegin "${FUNCNAME[0]}"
  writeMsg log "Setting DB2_EVALUNCOMMITTED=YES ..."
  setOut=`su - $DB_ADMIN_USER -c 'db2set DB2_EVALUNCOMMITTED=YES'`
  [ "$setOut" ] && writeMsg log "$setOut"
  writeMsg log "Setting DB2_SKIPINSERTED=YES ..."
  setOut=`su - $DB_ADMIN_USER -c 'db2set DB2_SKIPINSERTED=ON'`
  [ "$setOut" ] && writeMsg log "$setOut"
  writeMsg log "Setting DB2_SKIPDELETED=YES ..."
  setOut=`su - $DB_ADMIN_USER -c 'db2set DB2_SKIPDELETED=ON'`
  [ "$setOut" ] && writeMsg log "$setOut"
  logFnEnd "${FUNCNAME[0]}"
}

configureDB2Instance()
{
  logFnBegin "${FUNCNAME[0]}"
  instDb2=$1
  lastrc=0
  fnRc=0

  if [[ $DB2INST_CONFIGURE = "yes" ]]
  then
    writeMsg log "Setting DB2_EXTENDED_OPTIMIZATION=ON ..."
    setOut=`su - $DB_ADMIN_USER -c 'db2set DB2_EXTENDED_OPTIMIZATION=ON'`
    [ "$setOut" ] && writeMsg log "$setOut"
    writeMsg log "Updating dbm cfg ..."
    cfgOut=`su - $DB_ADMIN_USER -c 'db2 update dbm cfg using HEALTH_MON OFF QUERY_HEAP_SZ 512 ASLHEAPSZ 512'`
    [ "$cfgOut" ] && writeMsg log "$cfgOut"
    writeMsg log "Updating cli cfg ..."
    cfgOut=`su - $DB_ADMIN_USER -c 'db2 UPDATE CLI CONFIGURATION FOR SECTION COMMON USING FET_BUF_SIZE 256K SQL_ATTR_TXN_ISOLATION 2 SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION 1 SQL_ATTR_CURSOR_HOLD SQL_CURSOR_HOLD_OFF'`
    [ "$cfgOut" ] && writeMsg log "$cfgOut"
  fi

  setRegistryValuesForDb2Locking

  if [[ $instDb2 = "no" ]]
  then 
    writeMsg log "Starting $DB_ADMIN_USER instance ..."
    startOut=`su - $DB_ADMIN_USER -c "db2start"`
    lastrc=$?
    writeMsg log "$startOut"
    if [[ $lastrc -ne 0 &&  $lastrc -ne 1 ]]
    then
      writeMsg log "Warning: Unable to Start $DB_ADMIN_USER instance"
      fnRc=1
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

copyMasthead()
{
  logFnBegin "${FUNCNAME[0]}"
  compName=$1
  fnRc=0
  source=$BES_MASTHEAD_FILE
  etcCompFolder=$DEF_BES_ETC
  if [[ $compName = "$DEF_RPM_WR_PREFIX" ]]
  then
    etcCompFolder=$DEF_WR_ETC
  elif [[ $compName = "$DEF_RPM_AGT_PREFIX" ]]
  then
    etcCompFolder=$DEF_AGT_ETC
  fi
  dest=$etcCompFolder$DEF_BES_ACTIONSITE_FILE
  if [[ $compName != "$DEF_RPM_SRV_PREFIX"  && -f $DEF_BES_ETC/$DEF_BES_ACTIONSITE_FILE ]]
  then
    source=$DEF_BES_ETC/$DEF_BES_ACTIONSITE_FILE
  fi

  if [[ -f $source ]]
  then
    mkdir -p $etcCompFolder 2>> $DEF_BES_LOG_FILE
    lastrc=0
    if [ "$source" != "$dest" ]
    then
      \cp -f "$source" "$dest"  2>> $DEF_BES_LOG_FILE
      lastrc=$?
    fi
    ##The copy command returns:
    ##    0 if the copy file is success
    ##    not 0 in case of failure
    if [[ $lastrc -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0017E' \"$source\" \"$dest\"`"
      fnRc=1
    else
      writeMsg log "`nls_replace 'TEM0033I' \"$dest\"`"
    fi
  else
    writeMsg both "`nls_replace 'TEM0024E' \"$BES_MASTHEAD_FILE\"`"
    fnRc=1
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

runBesAdmin()
{
  logFnBegin "${FUNCNAME[0]}"
  cmd=$1
  cmdOpt=$2
  fnRc=0
  lastrc=0
  adminTool="$DEF_BES_BIN_ROOT/BESAdmin"
  adminToolInstaller="$DEF_BES_REPOS_FOLDER/BESAdmin"
  adminToolRunCommand="$adminTool $cmd $cmdOpt"
  adminToolInstallerRunCommand="$adminToolInstaller $cmd $cmdOpt"
  BESClientActionMastheadPath="$DEF_BES_ETC/$DEF_BES_ACTIONSITE_FILE"
  msgSuccess=""
  msgError=""
  options=""
  if [[ -f "$adminTool" ]]
  then
    runCmd="$adminToolRunCommand"
  elif [[ -f $adminToolInstaller ]]
  then
    runCmd="$adminToolInstallerRunCommand"
  else
    writeMsg both "`nls_replace 'TEM0037E' \"BESAdmin\" \"$DEF_BES_BIN_ROOT\" \"$DEF_BES_REPOS_FOLDER\"`"
    fnRc=1
    logFnEnd "${FUNCNAME[0]}"
    return $fnRc
  fi

  case $cmd in
  -processauthfile    )
      msgSuccess="`nls_replace 'TEM0050I'`"
      msgError="`nls_replace 'TEM0051E'`"
      BES_LIBPATH=$DEF_BES_REPOS_FOLDER
      BES_MASTHEAD_FILE="$BES_LIC_FOLDER$DEF_BES_MASTHEAD_FILE"
      options="-authLicenseLocation:\"$BES_AUTH_FILE\" -privateKeyPswd:\"$BES_LICENSE_PVK_PWD\" -privateKeySize:$PVK_KEY_SIZE -serverDNSName:\"$SRV_DNS_NAME\" -outLocation:\"$BES_LIC_FOLDER\""
      if [[ $SUBMIT_LIC_REQUEST != "yes" ]]
      then
        options="$options -saveRequest:yes"
      else
        options="$options -fxfcharencoding:\"windows-$ENCODE_VALUE\""
        options="$options -advPortNumber:\"$BES_SERVER_PORT\" -advGatherSchedule:\"$BES_GATHER_INTERVAL\" -advRequireFIPScompliantCrypto:\"$ENABLE_FIPS\" -advController:\"$LOCK_CONTROLLER\" -advInitialLockState:\"$INITIAL_LOCK\" -advInitialLockDuration:\"$LOCK_DURATION\" -advActionLockExemptionURL:\"$EXCEPTION_URL\" -advRequireEnhancedSecurity:\"false\" -advRequireSHA2IntegrityChecks:\"false\" -advArchiveAllowUTF8:\"$ENABLE_ARCHIVE_UTF8\""
        if [[ $USE_PROXY = "true" ]]
		then
			options="$options -proxyHost:\"$PROXY_HOST\" -proxyPort:\"$PROXY_PORT\""
			if [[ $PROXY_USER != "" ]]
			then
				options="$options -proxyUser:\"$PROXY_USER\" -proxyPassword:\"$PROXY_PWD\""
			fi
			if [[ $PROXY_SECTUNNEL != "" ]]
			then
				options="$options -proxySecTunnel:\"$PROXY_SECTUNNEL\""
			fi
			if [[ $PROXY_METH != "" && $PROXY_METH != "all" ]]
			then
				options="$options  -proxyAuthMeth:\"$PROXY_METH\""
			fi
		fi
      fi
      ;;
  -processmasthead    )
      msgSuccess="`nls_replace 'TEM0147I'`"
      msgError="`nls_replace 'TEM0148E'`"
      BES_LIBPATH=$DEF_BES_REPOS_FOLDER
      options="-pvkLocation:\"$BES_LICENSE_PVK\" -privateKeyPswd:\"$BES_LICENSE_PVK_PWD\" -mastheadLocation:\"$BES_MASTHEAD_FILE\" -fxfcharencoding:\"windows-$ENCODE_VALUE\""
      ;;
  -makeevalmasthead   )
      msgSuccess="`nls_replace 'TEM0054I'`"
      msgError="`nls_replace 'TEM0055E'`"
      BES_LIBPATH=$DEF_BES_REPOS_FOLDER
      BES_MASTHEAD_FILE="$BES_LIC_FOLDER$DEF_BES_MASTHEAD_FILE"
      options="-evalMastheadFirstName:\"$CREDENTIAL_USER_FIRSTNAME\" -evalMastheadLastName:\"$CREDENTIAL_USER_LASTNAME\" -evalMastheadEmailAddress:\"$CREDENTIAL_EMAIL\" -evalMastheadOrganization:\"$CREDENTIAL_ORG\" -evalMastheadPassword:\"$BES_LICENSE_PVK_PWD\" -evalMastheadKeySize:$PVK_KEY_SIZE -evalMastheadServerName:\"$SRV_DNS_NAME\" -evalMastheadServerPort:\"$BES_SERVER_PORT\" -outLocation:\"$BES_LIC_FOLDER\" -fxfcharencoding:\"windows-$ENCODE_VALUE\""
      if [[ $USE_PROXY = "true" ]]
      then
        options="$options -proxyHost:\"$PROXY_HOST\" -proxyPort:\"$PROXY_PORT\""
		if [[ $PROXY_USER != "" ]]
	    then
		    options="$options -proxyUser:\"$PROXY_USER\" -proxyPassword:\"$PROXY_PWD\""
        fi
		if [[ $PROXY_SECTUNNEL != "" ]]
	    then
			options="$options -proxySecTunnel:\"$PROXY_SECTUNNEL\""
		fi
		if [[ $PROXY_METH != "" && $PROXY_METH != "all" ]]
		then
			options="$options  -proxyAuthMeth:\"$PROXY_METH\""
		fi
      fi
                     ;;
  -processcertificate )
      msgSuccess="`nls_replace 'TEM0052I'`"
      msgError="`nls_replace 'TEM0053E'`"
      BES_LIBPATH=$DEF_BES_REPOS_FOLDER
      BES_MASTHEAD_FILE="$BES_LIC_FOLDER$DEF_BES_MASTHEAD_FILE"
      options="-crtLocation:\"$BES_CERT_FILE\" -pvkLocation:\"$BES_LICENSE_PVK\" -privateKeyPswd:\"$BES_LICENSE_PVK_PWD\" -outLocation:\"$BES_LIC_FOLDER\" -advPortNumber:\"$BES_SERVER_PORT\" -advGatherSchedule:\"$BES_GATHER_INTERVAL\" -advRequireFIPScompliantCrypto:\"$ENABLE_FIPS\" -advController:\"$LOCK_CONTROLLER\" -advInitialLockState:\"$INITIAL_LOCK\" -advInitialLockDuration:\"$LOCK_DURATION\" -advActionLockExemptionURL:\"$EXCEPTION_URL\" -advRequireEnhancedSecurity:\"false\" -advRequireSHA2IntegrityChecks:\"false\" -advArchiveAllowUTF8:\"$ENABLE_ARCHIVE_UTF8\" -fxfcharencoding:\"windows-$ENCODE_VALUE\""
                      ;;
  -setproxy )
      msgSuccess="`nls_replace 'TEM0137I'`"
      msgError="`nls_replace 'TEM0138E'`"
      BES_LIBPATH=$DEF_BES_REPOS_FOLDER
      options="-sitePvkLocation:\"$BES_LICENSE_PVK\" -sitePvkPassword:\"$BES_LICENSE_PVK_PWD\" -proxy:\"$PROXY_HOST\":\"$PROXY_PORT\""
	  if [[ $PROXY_USER != "" ]]
	  then
		options="$options -user:\"$PROXY_USER\" -pass:\"$PROXY_PWD\""
      fi
	  if [[ $PROXY_EXLIST != "" && $PROXY_EXLIST != "none" ]]
	   then
		options="$options -exceptionlist:\"$PROXY_EXLIST\""
      fi
	  if [[ $PROXY_SECTUNNEL != "" ]]
	   then
		options="$options -proxysecuretunnel:\"$PROXY_SECTUNNEL\""
      fi
	  if [[ $PROXY_METH != "" && $PROXY_METH != "all" ]]
	   then
		options="$options  -proxyauthmethods:\"$PROXY_METH\""
      fi
	  if [[ $PROXY_DOWN != "" ]]
	   then
		options="$options  -proxydownstream:\"$PROXY_DOWN\""
      fi
                     ;;
  -testproxyconnection )
      msgSuccess="`nls_replace 'TEM0140I'`"
      msgError="`nls_replace 'TEM0141E'`"
      BES_LIBPATH=$DEF_BES_REPOS_FOLDER
      options="-proxyHost:\"$PROXY_HOST\""
	  if [[ $PROXY_PORT != "" ]]
	  then
		options="$options -proxyPort:\"$PROXY_PORT\""
      fi
	  if [[ $PROXY_USER != "" ]]
	  then
		options="$options -proxyUser:\"$PROXY_USER\" -proxyPassword:\"$PROXY_PWD\""
      fi
	  if [[ $PROXY_SECTUNNEL != "" ]]
	   then
		options="$options -proxySecTunnel:\"$PROXY_SECTUNNEL\""
      fi
	  if [[ $PROXY_METH != "" && $PROXY_METH != "all" ]]
	   then
		options="$options  -proxyAuthMeth:\"$PROXY_METH\""
      fi
	  if [[ $TEST_PROXY = "fips" ]]
	   then
		options="$options  -fips"
      fi
                     ;;
  -preinstall )
    options=""
    if [[ $cmdOpt = "-dbbesserver" ]]
    then
      options="$options -dbname:\"$BES_DB_NAME\""
      msgSuccess="`nls_replace 'TEM0043I'`"
      [[ $BES_REUSE_DB != "true" ]] || msgSuccess="`nls_replace 'TEM0103I'`"
      msgError="`nls_replace 'TEM0045E'`"
      [[ $BES_REUSE_DB != "true" ]] || msgError="`nls_replace 'TEM0104E'`"
      if [[ $BES_REUSE_DB != "true" ]]; then
        writeMsg both "`nls_replace 'TEM0041I'`"
      else
        writeMsg both "`nls_replace 'TEM0102I'`"
      fi
    else
      options="$options -dbname:\"$WR_DB_NAME\""
      msgSuccess="`nls_replace 'TEM0044I'`"
      [[ $BES_REUSE_DB != "true" ]] || msgSuccess="`nls_replace 'TEM0106I'`"
      msgError="`nls_replace 'TEM0046E'`"
      [[ $BES_REUSE_DB != "true" ]] || msgError="`nls_replace 'TEM0107E'`"
      if [[ $BES_REUSE_DB != "true" ]]; then
        writeMsg both "`nls_replace 'TEM0042I'`"
      else
        writeMsg both "`nls_replace 'TEM0105I'`"
      fi
    fi
    BES_LIBPATH=$DEF_BES_REPOS_FOLDER
    if [[ $LOCAL_DATABASE = "false" ]]
    then
      if [[ $DB_TARGET = "db2" ]]
      then
        options="$options -db2ClientUsername:\"$DB_ADMIN_USER\""
      fi
      options="$options -remoteDB:\"$DB_HOSTNAME\""
    fi
    options="$options -dbUsername:\"$DB_CONN_USER\" -dbPassword:\"$DB_CONN_PWD\" -dbPort:\"$DB_PORT\""
    if [[ $BES_REUSE_DB = "true" ]]
    then
      options="$options -reuseDb"
    fi
                      ;;
  -enforcepasswordpolicy )
    BES_LIBPATH=$DEF_BES_BIN_ROOT
    msgSuccess="`nls_replace 'TEM0163I'`"
    msgError="`nls_replace 'TEM0164E'`"
    options="-sitePvkLocation=\"$BES_LICENSE_PVK\" -sitePvkPassword:\"$BES_LICENSE_PVK_PWD\" -enforcepasswordpolicy"
    ;;
  -install )
    msgSuccess="`nls_replace 'TEM0048I'`"
    msgError="`nls_replace 'TEM0049E'`"
    writeMsg both "`nls_replace 'TEM0047I'`"
    BES_LIBPATH=$DEF_BES_BIN_ROOT
    if [[ $LOCAL_DATABASE = "false" ]]
    then
      options="$options -remoteDB:\"$DB_HOSTNAME\""
    else
      options="$options -databaseDNS:\"$SRV_DNS_NAME\""
    fi
    if [[ $DB_TARGET = "db2" ]]
    then
      options="-dbUsername:\"$DB_CONN_USER\" -dbPassword:\"$DB_CONN_PWD\" -dbname:\"$BES_DB_NAME\" -mastheadLocation:\"$DEF_BES_ETC$DEF_BES_ACTIONSITE_FILE\" -sitePvkLocation=\"$BES_LICENSE_PVK\" -sitePvkPassword:\"$BES_LICENSE_PVK_PWD\" -dbPort:\"$DB_PORT\""
      if [[ $cmdOpt = "-isReplicated" ]]
      then
        options="$options -masterDatabaseDNS:\"$MASTER_DNS\" -masterDbPort:\"$DB2_MASTER_PORT\" -serverURL:\"http://$SRV_DNS_NAME:$BES_SERVER_PORT\"  -masterDbUsername:\"$DB2_MASTER_USER\" -masterDbPassword:\"$DB2_MASTER_PWD\""
      else
        options="$options -username:\"$TEM_USER_NAME\" -password:\"$TEM_USER_PWD\""
      fi
      if [[ $USE_PROXY = "true" ]]
      then
        options="$options -proxyHost:\"$PROXY_HOST\" -proxyPort:\"$PROXY_PORT\""
        if [[ $PROXY_USER != "" ]]
        then
          options="$options -proxyUser:\"$PROXY_USER\" -proxyPassword:\"$PROXY_PWD\""
        fi
        if [[ $PROXY_SECTUNNEL != "" ]]
        then
          options="$options -proxySecTunnel:\"$PROXY_SECTUNNEL\""
        fi
        if [[ $PROXY_METH != "" && $PROXY_METH != "all" ]]
        then
          options="$options  -proxyAuthMeth:\"$PROXY_METH\""
        fi
      fi
    else
      # Replication and proxy are not yet supported on SQL Server
      options="-dbUsername:\"$DB_CONN_USER\" -dbPassword:\"$DB_CONN_PWD\" -dbname:\"$BES_DB_NAME\" -mastheadLocation:\"$DEF_BES_ETC$DEF_BES_ACTIONSITE_FILE\" -sitePvkLocation=\"$BES_LICENSE_PVK\" -sitePvkPassword:\"$BES_LICENSE_PVK_PWD\" -dbPort:\"$DB_PORT\" -username:\"$TEM_USER_NAME\" -password:\"$TEM_USER_PWD\""
    fi
                      ;;
  -initializewebreportsuser   )
      msgSuccess="`nls_replace 'TEM0080I'`"
      msgError="`nls_replace 'TEM0081W'`"
      BES_LIBPATH=$DEF_WR_BIN_ROOT
      BESClientActionMastheadPath=$DEF_WR_ETC/$DEF_BES_ACTIONSITE_FILE
      options="-dbname:\"$WR_DB_NAME\" -dbUsername:\"$DB_CONN_USER\" -dbPassword:\"$DB_CONN_PWD\" -dbPort:\"$DB_PORT\" -username:\"$TEM_USER_NAME\" -password:\"$TEM_USER_PWD\" -roleID:1"
      if [[ $LOCAL_DATABASE = "false" ]]
      then
        options="$options -remoteDB:\"$DB_HOSTNAME\" -dbPort:\"$DB_PORT\""
      fi
                      ;;
  -ensurecredentials )
      # In the upgrade phase the installer would use the BESAdmin already
      # installed but if a client is upgrading from 9.2 then the function
      # needed to ensure the credentials would not exist on that BESAdmin so we
      # have to use the BESAdmin that we ship with the ServerInstaller/repos
      runCmd="$adminToolInstallerRunCommand"
      LD_LIBRARY_PATH=$DEF_BES_REPOS_FOLDER:$LD_LIBRARY_PATH
      export LD_LIBRARY_PATH
      msgError="`nls_replace 'TEM0150W'`"
      options="-sitePvkPassword:\"$BES_LICENSE_PVK_PWD\" -sitePvkLocation:\"$BES_LICENSE_PVK\""
                      ;;
  -generateWRCertificate )
      msgSuccess="`nls_replace 'TEM0166I'`"
      msgError="`nls_replace 'TEM0167E'`"
      options="-hostname:\"$SRV_DNS_NAME\" -path:\"$DEF_WR_PEM\""
      ;;
  -createwebuicredentials )
      msgSuccess="`nls_replace 'TEM0169I'`"
      msgError="`nls_replace 'TEM0170E'`"
      options="-sitePvkLocation=\"$BES_LICENSE_PVK\" -sitePvkPassword:\"$BES_LICENSE_PVK_PWD\" -webuiCertDir=\"$DEF_WEBUI_ROOT\" -webuiHostname=\"$WEBUI_DNS_NAME\" -f"
      ;;
  * )
      writeMsg both "`nls_replace 'TEM0023E' \"runBesAdmin $cmd\"`"
      fnRc=1
      logFnEnd "${FUNCNAME[0]}"
      return $fnRc
      ;;
  esac
  export BES_LIBPATH
  export BESClientActionMastheadPath
  runCmd="$runCmd $options"

  toLogCmd="$runCmd"
  toLogCmd=$( echo $toLogCmd | sed "s|-privateKeyPswd:\"$BES_LICENSE_PVK_PWD\"|-privateKeyPswd:\"********\"|g" )
  toLogCmd=$( echo $toLogCmd | sed "s|-proxyPassword:\"$PROXY_PWD\"|-proxyPassword:\"********\"|g" )
  toLogCmd=$( echo $toLogCmd | sed "s|-evalMastheadPassword:\"$BES_LICENSE_PVK_PWD\"|-evalMastheadPassword:\"********\"|g" )
  toLogCmd=$( echo $toLogCmd | sed "s|-dbPassword:\"$DB_CONN_PWD\"|-dbPassword:\"********\"|g" )
  toLogCmd=$( echo $toLogCmd | sed "s|-sitePvkPassword:\"$BES_LICENSE_PVK_PWD\"|-sitePvkPassword:\"********\"|g" )
  toLogCmd=$( echo $toLogCmd | sed "s|-masterDbPassword:\"$DB2_MASTER_PWD\"|-masterDbPassword:\"********\"|g" )
  toLogCmd=$( echo $toLogCmd | sed "s|-password:\"$TEM_USER_PWD\"|-password:\"********\"|g" )
  writeMsg log "$toLogCmd"

  eval $runCmd >>  $DEF_BES_LOG_FILE 2>&1
  lastrc=$?
  ##The besadmin returns:
  ##    0 if the action has been completed successfully
  ##    not 0 in all the other cases
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg log "`nls_replace 'TEM0030E' \"runBesAdmin $cmd\"`"
    writeMsg both "$msgError"
    fnRc=1
  else
    writeMsg log "`nls_replace 'TEM0031I' \"runBesAdmin $cmd\"`"
    writeMsg both "$msgSuccess"
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

initWRDB()
{
  logFnBegin "${FUNCNAME[0]}"
  fnRc=0
  lastrc=0
  cmdOpt=$1
  wrInitTool="$DEF_WR_BIN_ROOT/BESWebReportsServer"
  options=""
  logOptions=""
  if [[ $cmdOpt = "-upgrade" ]]
  then
    logOptions="-initializeDB -upgrade ********"
    options="-initializeDB -upgrade \"$DB_CONN_PWD\""
  else
    logOptions="-initializeDB \"$WR_DB_NAME\" \"$DB_CONN_USER\" ********"
    options="-initializeDB \"$WR_DB_NAME\" \"$DB_CONN_USER\" \"$DB_CONN_PWD\""
  fi
  logOptions="$logOptions \"$DB_HOSTNAME\" \"$DB_PORT\""
  options="$options \"$DB_HOSTNAME\" \"$DB_PORT\""

  writeMsg log "$wrInitTool $logOptions"
  writeMsg both "`nls_replace 'TEM0057I'`"

  runCmd="DB2INSTANCE=$DB2_INSTANCE_NAME BES_LIBPATH=$DEF_WR_BIN_ROOT $wrInitTool $options"
  eval $runCmd >>  $DEF_BES_LOG_FILE 2>&1
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0059E'`"
    fnRc=1
  else
    writeMsg both "`nls_replace 'TEM0058I'`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

upgradeSrvDatabase()
{
  logFnBegin "${FUNCNAME[0]}"
  fnRc=0
  writeMsg both "`nls_replace 'TEM0047I'`"
  adminToolScript="$DEF_BES_BIN_ROOT/BESAdmin.sh"
  options="-upgrade"
  if [[ $ASK_PVK_CREDENTIALS !=  "false" ]]
  then
    options="$options -sitePvkLocation:\"$BES_LICENSE_PVK\" -sitePvkPassword:\"$BES_LICENSE_PVK_PWD\""
  fi
  runCmd="$adminToolScript $options"
  toLogCmd="$runCmd"
  toLogCmd=$( echo $toLogCmd | sed "s|-sitePvkPassword:\"$BES_LICENSE_PVK_PWD\"|-sitePvkPassword:\"********\"|g" )
  writeMsg log "$toLogCmd"
  eval $runCmd >> $DEF_BES_LOG_FILE 2>&1
  lastrc=$?
  if [[ $lastrc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0049E'`"
    fnRc=1
  else
    writeMsg both "`nls_replace 'TEM0048I'`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

createDatabases()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $COMPONENT_SRV = "true" ]]
  then
    runBesAdmin "-preinstall" "-dbbesserver"
    checkFatalerror $?
  fi

  if [[ $COMPONENT_WR = "true" ]]
  then
    runBesAdmin "-preinstall" "-dbwebreport"
    checkFatalerror $?
  fi
  logFnEnd "${FUNCNAME[0]}"
}

checkFatalerror()
{
  logFnBegin "${FUNCNAME[0]}"
  returnCode=$1
  if [[ $returnCode -ne 0 ]]
  then
    writeMsg log "Exit Code= $returnCode"
    writeMsg both "`nls_replace 'TEM0032E' \"$PRODUCT_NAME\" \"$DEF_BES_LOG_FILE\"`"
    exit 1
  fi
  logFnEnd "${FUNCNAME[0]}"
}

#Installation flow Blocks
######################################################

collectDatabaseInput()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $LOCAL_DATABASE = "false" ]]
  then
    specifyDbHostname
    specifyDbPort
    specifyDbRemoteUser
    specifyDbRemotePwd
  else
    DB_CONN_USER=$DB_ADMIN_USER
    DB_CONN_PWD=$DB_ADMIN_PWD
    DB_HOSTNAME=$SRV_DNS_NAME
    specifyDbPort
    if [[ $DB_TARGET = "db2" ]]
    then
      configureDB2Instance "$INSTALL_DB2"
    fi
  fi

  if [[ $COMPONENT_WEBUI = "true" && $COMPONENT_WR = "true" && $COMPONENT_SRV = "false" ]]
  then
    writeMsg both "`nls_replace 'TEM0172I'`"
    specifyWebUIDbHostname
    specifyWebUIDbPort
    specifyWebUIDbAdminUser
    specifyWebUIDbPwd
  fi

  if [[ $SINGLE_DATABASE = "false" ]]
  then
    specifyMasterDBHost
    specifyMasterDbPort
    specifyMasterDB2User
    specifyMasterDB2Pwd

    if [[ "$DB_CONN_USER" != "$DB2_MASTER_USER" || "$DB_REPLICA_PWD_SHA256" != "$DB2_MASTER_PWD_SHA256" || "$DB_PORT" != "$DB2_MASTER_PORT" ]]
    then
      replicationCredentialWarning
      if [[ $IGNORE_REPL_CRED_WARNING = "no" ]]
      then
        writeMsg both "`nls_replace 'TEM0001W'`"
        exit 1
      fi
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
}

collectWRUserData()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $IS_EVALUATION = "false" ]] && [[ $COMPONENT_WR = "true" ]]
  then
    useRootForWR

    if [[ $WR_USEROOT = "false" ]]
    then
      chooseNonRootUserNameForWR
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
}

collectComponentsInput()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $COMPONENT_SRV = "true" ]]
  then
    chooseBesWWWRoot
  else
    BES_WWW_FOLDER=""
  fi

  if [[ $COMPONENT_WR = "true" ]]
  then
    chooseWRWWWRoot
    chooseWRPort
  else
    WR_WWW_FOLDER=""
    WR_WWW_PORT=""
  fi

  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    if [[ $COMPONENT_WR = "false" ]]
    then
      chooseWebUIPort
      chooseAndVerifyPort "webuiredirect" "$WEBUI_PORT"
    else
      chooseAndVerifyPort "webui" "$WR_WWW_PORT" "$DEF_WR_REDIRECT_PORT"
      chooseAndVerifyPort "webuiredirect" "$WR_WWW_PORT" "$DEF_WR_REDIRECT_PORT" "$WEBUI_PORT"
    fi
    if [[ $COMPONENT_SRV = "false" ]]
    then
      chooseWebUISrcCertFolder
    fi
  else
    WEBUI_SRC_CERT_FOLDER=""
    WEBUI_PORT=""
    WEBUI_REDIRECT_PORT=""
  fi
  logFnEnd "${FUNCNAME[0]}"
}

installFromMasthead()
{
  logFnBegin "${FUNCNAME[0]}"
  getSigningKey

  getSigningKeyPwd

  getMastheadFile

  logFnEnd "${FUNCNAME[0]}"
}

collectPvkCredentials()
{
  logFnBegin "${FUNCNAME[0]}"
  getSigningKey

  getSigningKeyPwd
  logFnEnd "${FUNCNAME[0]}"
}

collectDB2Input()
{
  logFnBegin "${FUNCNAME[0]}"
  db2BaseVarSet
  installDB2Conf
  if [[ $CONTINUE_INSTALL_DB2 = "no" ]]
  then
    writeMsg both "`nls_replace 'TEM0001W'`"
    exit 1
  fi
  db2BaseVarCheck

  checkDB2OsPrereqs
  if [[ $DB2_SETUP_FILE = "" ]]
  then
    DB2_SETUP_FILE=$(getDb2BundledSetup)
  fi

  if [[ $DB2_SETUP_FILE = "" ]]
  then
    getDB2SetupFile
  fi

  specifyDB2Pwd
  logFnEnd "${FUNCNAME[0]}"
}

db2BaseVarCheck()
{
  logFnBegin "${FUNCNAME[0]}"
  isError="false"
  userExists "$DB2_INSTANCE_NAME"
  [[ $? -eq 0 ]] && { writeMsg both "`nls_replace 'TEM0113E' \"$DB2_INSTANCE_NAME\"`"; isError="true"; }

  userExists "$DB2_FENCED_USERNAME"
  [[ $? -eq 0 ]] && { writeMsg both "`nls_replace 'TEM0113E' \"$DB2_FENCED_USERNAME\"`"; isError="true"; }

  DB2_INSTALL_DIR=$(folderExists $DB2_INSTALL_DIR)
  [[ $? -eq 0 ]] && { writeMsg both "`nls_replace 'TEM0114E' \"$DB2_INSTALL_DIR\"`"; isError="true"; }

  isPortInUse "$DB_PORT"
  [[ $? -eq 0 ]] && { writeMsg both "`nls_replace 'TEM0122E' \"$DB_PORT\"`"; isError="true"; }

  [[ $isError = "true" ]] && { checkFatalerror "1"; }
  logFnEnd "${FUNCNAME[0]}"
}

db2BaseVarSet()
{
  logFnBegin "${FUNCNAME[0]}"
  [ "$DB2_INSTANCE_NAME" ] || DB2_INSTANCE_NAME=$DEF_DB_ADMIN_USER
  addResponseFileEntry "DB2_INSTANCE_NAME" "$DB2_INSTANCE_NAME"
  DB_ADMIN_USER=$DB2_INSTANCE_NAME
  DB2INSTANCE=$DB2_INSTANCE_NAME
  export DB2INSTANCE

  [ "$DB2_FENCED_USERNAME" ] || DB2_FENCED_USERNAME=$DEF_DB2_FENCED_USERNAME
  addResponseFileEntry "DB2_FENCED_USERNAME" "$DB2_FENCED_USERNAME"

  [ "$DB2_INSTALL_DIR" ] || DB2_INSTALL_DIR=$DEF_DB2_INSTALL_DIR
  addResponseFileEntry "DB2_INSTALL_DIR" "$DB2_INSTALL_DIR"

  [ "$DB_PORT" ] || DB_PORT=$DEF_DB_PORT
  addResponseFileEntry "DB_PORT" "$DEF_DB_PORT"
  logFnEnd "${FUNCNAME[0]}"
}

setEncodeFromMastheadOrRewrite()
{
  logFnBegin "${FUNCNAME[0]}"
  charset=$(extractFxfCharset)
  if [[ $charset = "" ]]
  then
    # we have an old masthead withoug the fxf-encoding so we ask the encoding
    # and then rewrite the masthead
    specifyEncoding
    runBesAdmin "-processmasthead"
  else
    ENCODE_VALUE=$charset
  fi
  logFnEnd "${FUNCNAME[0]}"
}

installStart()
{
  logFnBegin "${FUNCNAME[0]}"
  isRc=0

  ##Components already installed will not be reinstalled
  unsetInstalledComponents

  selectComponents

  if [[ $DB_TARGET = "db2" && $COMPONENT_SRV = "true" ]] # Replication is not supported with SQL Server database
  then
    selectDBReplType
    if [[ $COMPONENT_WEBUI = "true" && $SINGLE_DATABASE = "false" ]]
    then
      writeMsg both "`nls_replace 'TEM0171E'`"
      exit 1
    fi
  else
    SINGLE_DATABASE="true"
  fi

  if [[ $COMPONENT_SRV = "true" || $COMPONENT_WR = "true" ]]
  then
    selectDBLocation
  else
    LOCAL_DATABASE="false"
  fi

  collectComponentsInput

  if [[ $DB_TARGET = "db2" ]]
  then
    [ "$LOCAL_DATABASE" = "true" ] && installDB2Warning || INSTALL_DB2="no"

    if [[ $INSTALL_DB2 = "exit" ]]
    then
      writeMsg both "`nls_replace 'TEM0001W'`"
      exit 1
    elif [[ $INSTALL_DB2 = "yes" ]]
    then
      writeMsg log "DB2 Not Installed"
      DB2INST_CONFIGURE="yes"
      collectDB2Input
      checkDb2suid "$DB2_INSTALL_DIR"
    elif [[ $COMPONENT_SRV = "true" || $COMPONENT_WR = "true" ]]
    then
      writeMsg log "DB2 Installed"
      specifyDB2Instance
      specifyDBAdminUser
      updateDb2PathVariables
      if [[ $LOCAL_DATABASE = "true" ]]
      then
        specifyDBAdminPwd
        chooseInstanceConf
      fi
    fi
  fi

  checkDiskSpace
  if [[ $PREREQ_SPACE_MISSING = "true" ]]
  then
    prereqSpaceWarning
    if [[ $IGNORE_SPACE_WARNING = "no" ]]
    then
      writeMsg both "`nls_replace 'TEM0001W'`"
      exit 1
    fi
  fi

  if [[ $DB_TARGET = "db2" && $INSTALL_DB2 = "yes" ]]
  then
    configureDB2RespFile "$DEF_BES_DB2_RESP_TEMPLATE" "$DEF_BES_DB2_RESP"
    installDB2 "$DB2_SETUP_FILE" "$DEF_BES_DB2_RESP"
    checkFatalerror $?
    verifyDB2Install "$DB2_INSTALL_DIR/bin"
    checkFatalerror $?
    copyDB2LicenseDir
    updateDb2PathVariables
    DB_ADMIN_PWD=$( runObfuscatePassword "$DB2_USERS_PWD" )
  fi

  if [[ $DB_TARGET = "mssql" && "$LOCAL_DATABASE" = "true" && ( $COMPONENT_SRV = "true" || $COMPONENT_WR = "true" ) ]]
  then
    isSqlServerDetected=$(isSqlServerInstalled)
    if [[ $isSqlServerDetected = "false" ]]
    then
      writeMsg both "`nls_replace 'SQLServerNotInstalledMsg'`"
      exit 1
    fi
    specifyDBAdminUser
    specifyDBAdminPwd
  fi

  if [[ ( $COMPONENT_SRV = "true" && $SINGLE_DATABASE = "true" ) || ( $COMPONENT_WR = "true" ) ]]
  then
    chooseAdminUserName
    chooseAdminUserPwd
  else
    TEM_USER_NAME=""
    TEM_USER_PWD=""
  fi

  if [[ $DB_TARGET = "db2" && ( $COMPONENT_SRV = "true" || $COMPONENT_WR = "true" ) ]]
  then
    PREREQ_DB2_OK=$(checkDB2Version)
    if [[ $PREREQ_DB2_OK = "false" ]]
    then
      prereqDB2Warning
      if [[ $IGNORE_DB2_WARNING = "no" ]]
      then
        writeMsg both "`nls_replace 'TEM0001W'`"
        exit 1
      fi
    fi
  fi

  chooseFirewallConfig

  if [[ $COMPONENT_SRV = "true" && $SINGLE_DATABASE = "true" ]]
  then
    selectSetupType
    collectAndTestProxyInput
    case $BES_SETUP_TYPE in
      authfile  )
          installFromAuthFile
          let "isRc=isRc+$?"
          getMastheadHostAndPort;;
      prodlic   )
          installFromProdLic
          let "isRc=isRc+$?"
          getMastheadHostAndPort
          SRV_DNS_NAME=$MASTHEAD_HOST;;
      masthead  )
          installFromMasthead
          getMastheadHostAndPort
          SRV_DNS_NAME=$MASTHEAD_HOST
          BES_SERVER_PORT=$MASTHEAD_PORT
          setEncodeFromMastheadOrRewrite;;
    esac
    checkFatalerror $isRc
    let WEBUI_APPSERVER_PORT=BES_SERVER_PORT+4
    if [[ $COMPONENT_WEBUI = "true" ]]
    then
      WEBUI_DNS_NAME="$SRV_DNS_NAME"
    fi
  elif [[ $COMPONENT_SRV = "true" && $SINGLE_DATABASE = "false" ]]
  then
    collectAndTestProxyInput
    installFromMasthead
    getMastheadHostAndPort
    getSecondaryServerDnsName
    BES_SERVER_PORT=$MASTHEAD_PORT
    let WEBUI_APPSERVER_PORT=BES_SERVER_PORT+4
    setEncodeFromMastheadOrRewrite
  elif [[ $COMPONENT_SRV = "false" && $COMPONENT_WR = "false" ]]
  then
    getMastheadFile
    getMastheadHostAndPort
    SRV_DNS_NAME=$MASTHEAD_HOST
    getWebUIDnsName
  else
    getMastheadFile
    if [[ $COMPONENT_WEBUI = "true" ]]
    then
      getMastheadHostAndPort
      getWebUIDnsName
    fi
    getWebReportsHost
  fi
  logFnEnd "${FUNCNAME[0]}"
}

chooseAndVerifyPort()
{
  logFnBegin "${FUNCNAME[0]}"
  args=("$@")
  port="${args[0]}"

  valueToCheck=""

  while :
  do
    if [[ $port = "webui" ]]
    then
      chooseWebUIPort "false"
      valueToCheck="$WEBUI_PORT"
    else
      chooseWebUIRedirectPort "false"
      valueToCheck="$WEBUI_REDIRECT_PORT"
    fi

    found="no"
    for ((i=1; i<${#args[@]}; i++))
    do
      if [[ $valueToCheck = "${args[$i]}" ]]
      then
        found="yes"
        break
      fi
    done

    if [[ $found = "no" ]]
    then
      break
    else
      if [[ $port = "webui" ]]
      then
        WEBUI_PORT=""
      else
        WEBUI_REDIRECT_PORT=""
      fi
      writeMsg stdout "`nls_replace 'TEM0168E' \"$valueToCheck\"`"
    fi
  done

  if [[ $port = "webui" ]]
  then
    addResponseFileEntry "WEBUI_PORT" "$WEBUI_PORT"
  else
    addResponseFileEntry "WEBUI_REDIRECT_PORT" "$WEBUI_REDIRECT_PORT"
  fi
  logFnEnd "${FUNCNAME[0]}"
}

installStartEval()
{
  logFnBegin "${FUNCNAME[0]}"
  checkCleanEnv

  COMPONENT_SRV="true"
  COMPONENT_WR="true"
  COMPONENT_WEBUI="true"
  SINGLE_DATABASE="true"
  LOCAL_DATABASE="true"
  BES_WWW_FOLDER="$DEF_BES_ROOT"
  WR_WWW_FOLDER="$DEF_WR_ROOT"
  DB2INST_CONFIGURE="no"

  writeMsg stdout "$DEF_INPUT_SEPARATOR"
  writeMsg stdout "`nls_replace 'TEM0161I'`"
  collectCredentialInput

  getServerDnsName
  WEBUI_DNS_NAME="$SRV_DNS_NAME"
  chooseIdentificationPort
  chooseWRPort
  chooseAndVerifyPort "webui" "$WR_WWW_PORT" "$DEF_WR_REDIRECT_PORT"
  chooseAndVerifyPort "webuiredirect" "$WR_WWW_PORT" "$DEF_WR_REDIRECT_PORT" "$WEBUI_PORT"
  chooseFirewallConfig
  let WEBUI_APPSERVER_PORT=BES_SERVER_PORT+4

  if [[ $DB_TARGET = "db2" ]]
  then
    installDB2Warning
    if [[ $INSTALL_DB2 = "exit" ]]
    then
      writeMsg both "`nls_replace 'TEM0001W'`"
      exit 1
    elif [[ $INSTALL_DB2 = "yes" ]]
    then
      writeMsg log "DB2 Not Installed"
      collectDB2Input
      checkDb2suid "$DB2_INSTALL_DIR"
    else
      writeMsg log "DB2 Installed"
      specifyDB2Instance
      specifyDBAdminUser
      updateDb2PathVariables
      specifyCommonPwd
    fi
  fi
  selectKeySize

  checkDiskSpace
  if [[ $PREREQ_SPACE_MISSING = "true" ]]
  then
    prereqSpaceWarning
    if [[ $IGNORE_SPACE_WARNING = "no" ]]
    then
      writeMsg both "`nls_replace 'TEM0001W'`"
      exit 1
    fi
  fi

  if [[ $INSTALL_DB2 = "yes" ]]
  then
    configureDB2RespFile "$DEF_BES_DB2_RESP_TEMPLATE" "$DEF_BES_DB2_RESP"
    installDB2 "$DB2_SETUP_FILE" "$DEF_BES_DB2_RESP"
    checkFatalerror $?
    verifyDB2Install "$DB2_INSTALL_DIR/bin"
    checkFatalerror $?
    copyDB2LicenseDir
    updateDb2PathVariables
    DB_ADMIN_PWD=$( runObfuscatePassword "$DB2_USERS_PWD" )
    BES_LICENSE_PVK_PWD=$DB_ADMIN_PWD
    TEM_USER_PWD=$DB_ADMIN_PWD
  fi

  if [[ $DB_TARGET = "db2" ]]
  then
    PREREQ_DB2_OK=$(checkDB2Version)
    if [[ $PREREQ_DB2_OK = "false" ]]
    then
      prereqDB2Warning 
      if [[ $IGNORE_DB2_WARNING = "no" ]]
      then
        writeMsg both "`nls_replace 'TEM0001W'`"
        exit 1
      fi
    fi
  fi

  chooseLicFolder
  collectAndTestProxyInput

  specifyEncoding
  collectDatabaseInput

  TEM_USER_NAME="$DEF_TEM_USER_NAME_EVAL"
  BES_CERT_FILE="$BES_LIC_FOLDER$DEF_BES_CERT_FILE"
  BES_LICENSE_PVK="$BES_LIC_FOLDER$DEF_BES_LICENSE_PVK"

  writeMsg both  "`nls_replace 'TEM0160I'`"
  runBesAdmin "-makeevalmasthead"
  checkFatalerror $?
  logFnEnd "${FUNCNAME[0]}"
}

postInstall()
{
  logFnBegin "${FUNCNAME[0]}"
  piRc=0
  fnRc=0
  srvDbRc=0
  wrDbRc=0
  webuiConfRc=0
  configureFirewall

  if [[ $COMPONENT_SRV = "true" ]]
  then
    \cp -f "$DEF_BES_CONFIG_TEMPLATE" "$DEF_BES_CONFIG_TEMPLATE_EXT"  2>> $DEF_BES_LOG_FILE
    if [[ $SINGLE_DATABASE = "false" ]] 
    then
      addReplicationParms "$DEF_BES_CONFIG_TEMPLATE_EXT"
      createPasswordFile "$DEF_BES_ROOT/besserver.obf" "Replication_Database_Password" "$DB2_MASTER_PWD"
    fi
    updateConfigFile "$DEF_BES_CONFIG_TEMPLATE_EXT" "$DEF_BES_CONFIG_DEFAULT"
    \rm -f "$DEF_BES_CONFIG_TEMPLATE_EXT"

    createPasswordFile "$DEF_BES_ROOT/besserver.obf" "BESServer_Database_Password" "$DB_CONN_PWD"

    writeBesInfoFile "$DEF_BES_ROOT"

    cp "$DEF_BES_CONFIG_DEFAULT" "$DEF_BES_CONFIG"
    let "piRc=piRc+$?"

    if [[ $DB_TARGET = "db2" ]]
    then
      resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_SERVER[0]}"
      let "piRc=piRc+$?"

      resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_FILLDB[0]}"
      let "piRc=piRc+$?"

      resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_GATHERDB[0]}"
      let "piRc=piRc+$?"
    else
      removeLineFromFile "DB2INSTANCE=db2inst1" "$SERVICE_FOLDER/${SERVICE_SERVER[0]}"
      let "piRc=piRc+$?"
      removeLineFromFile "export DB2INSTANCE" "$SERVICE_FOLDER/${SERVICE_SERVER[0]}"
      let "piRc=piRc+$?"

      removeLineFromFile "DB2INSTANCE=db2inst1" "$SERVICE_FOLDER/${SERVICE_FILLDB[0]}"
      let "piRc=piRc+$?"
      removeLineFromFile "export DB2INSTANCE" "$SERVICE_FOLDER/${SERVICE_FILLDB[0]}"
      let "piRc=piRc+$?"
      
      removeLineFromFile "DB2INSTANCE=db2inst1" "$SERVICE_FOLDER/${SERVICE_GATHERDB[0]}"
      let "piRc=piRc+$?"
      removeLineFromFile "export DB2INSTANCE" "$SERVICE_FOLDER/${SERVICE_GATHERDB[0]}"
      let "piRc=piRc+$?"
    fi

    daemonReload

    resolveScriptTag "<DB2INSTANCE>" "$DB2_INSTANCE_NAME" "$DEF_BES_REPOS_FOLDER/BESAdmin.sh" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
    let "piRc=piRc+$?"
    resolveScriptTag "<DB2_ADMIN_USER>" "$DB_ADMIN_USER" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
    let "piRc=piRc+$?"

    if [[ $DB_TARGET = "mssql" ]]
    then
      removeLineFromFile "DB2INSTANCE=" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
      let "piRc=piRc+$?"
      removeLineFromFile "export DB2INSTANCE" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
      let "piRc=piRc+$?"
      removeLineFromFile "DB2_ADMIN_USER=" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
      let "piRc=piRc+$?"
      removeLineFromFile "export DB2_ADMIN_USER" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
      let "piRc=piRc+$?"
    fi

    resolveScriptTag "<DB2INSTANCE>" "$DB2_INSTANCE_NAME" "$DEF_BES_REPOS_FOLDER/Airgap.sh" "$DEF_BES_BIN_ROOT/Airgap.sh"
    let "piRc=piRc+$?"

    if [[ $DB_TARGET = "mssql" ]]
    then
      removeLineFromFile "DB2INSTANCE=" "$DEF_BES_BIN_ROOT/Airgap.sh"
      let "piRc=piRc+$?"
      removeLineFromFile "export DB2INSTANCE" "$DEF_BES_BIN_ROOT/Airgap.sh"
      let "piRc=piRc+$?"
    fi

    populateBESInstallers
    let "piRc=piRc+$?"

    if [[ $USE_PROXY = "true" ]]
    then
      runBesAdmin "-setproxy"
    fi

    if [[ $SINGLE_DATABASE = "true" ]]
    then
      runBesAdmin "-install"
      if [[ $BES_UPGRADE != "true" ]]
      then
        runBesAdmin "-enforcepasswordpolicy"
      fi
    else
      runBesAdmin "-install" "-isReplicated"
    fi
    srvDbRc=$?
    let "piRc=piRc+$srvDbRc"

    if [[ $srvDbRc -eq 0 ]]
    then
      startService "${SERVICE_SERVER[*]}"
      let "piRc=piRc+$?"

      startService "${SERVICE_FILLDB[*]}"
      let "piRc=piRc+$?"

      startService "${SERVICE_GATHERDB[*]}"
      let "piRc=piRc+$?"
    fi
  fi

  if [[ $COMPONENT_WR = "true" ]]
  then

    runBesAdmin "-generateWRCertificate"
    if [[ $COMPONENT_SRV = "true" ]]
    then
      \cp -f "$DEF_WR_CONFIG_TEMPLATE" "$DEF_WR_CONFIG_TEMPLATE_EXT"  2>> $DEF_BES_LOG_FILE
      addWRDataSourceParms "$DEF_WR_CONFIG_TEMPLATE_EXT"
      updateWrConfigFile "$DEF_WR_CONFIG_TEMPLATE_EXT" "$DEF_WR_CONFIG_DEFAULT"
      \rm -f "$DEF_WR_CONFIG_TEMPLATE_EXT"
    else
      updateWrConfigFile "$DEF_WR_CONFIG_TEMPLATE" "$DEF_WR_CONFIG_DEFAULT"
    fi

    createPasswordFile "$DEF_WR_ROOT/beswebreports.obf" "BESServer_Database_Password" "$DB_CONN_PWD"

    writeBesInfoFile "$DEF_WR_ROOT"

    \cp -f "$DEF_WR_CONFIG_DEFAULT" "$DEF_WR_CONFIG"
    let "piRc=piRc+$?"

    resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_WEBREPORT[0]}"
    let "piRc=piRc+$?"
    daemonReload

    initWRDB
    wrDbRc=$?
    let "piRc=piRc+$wrDbRc"

    if [[ $wrDbRc -eq 0 ]]
    then
      runBesAdmin "-initializewebreportsuser"

      fixBesCommonFilesPermissionBits

      if [[ $IS_EVALUATION = "false" ]] && [[ $WR_USEROOT = "false" ]]
      then
        changePermissionsForNonRootUser
      fi

      startService "${SERVICE_WEBREPORT[*]}"
      let "piRc=piRc+$?"
    fi
  fi

  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    # we need to stop the client before updating its configuration
    service "${SERVICE_CLIENT[0]}" status &> /dev/null
    if [[ $? -eq 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0179I'`"
      stopService "${SERVICE_CLIENT[*]}"
    fi

    # At this point the client is stopped. The client configuration setting will be updated with WebUI settings
    # if besclient.config does not exist, the WebUI configuration will be stored in besclient.config.default
    updateClientConfigFile

    mkdir "$DEF_WEBUI_ROOT/Mirror"
    mkdir "$DEF_WEBUI_ROOT/WebUI"

    webUIDstCertFolder="$DEF_WEBUI_ROOT/cert"
    if [[ $COMPONENT_SRV = "true" ]]
    then
      runBesAdmin "-createwebuicredentials"
      let "piRc=piRc+$?"
      # rename the WebUI certificates folder generated by BESAdmin
      mv "$DEF_WEBUI_ROOT/cert_$WEBUI_DNS_NAME" "$webUIDstCertFolder"
    else
      # if we are installing a standalone WebUI we need to copy the certificates issued by BES Root Server
      mkdir "$webUIDstCertFolder"

      # copy only what is strictly needed
      \cp -f "$WEBUI_SRC_CERT_FOLDER/auth_cert.crt" "$webUIDstCertFolder/auth_cert.crt"
      \cp -f "$WEBUI_SRC_CERT_FOLDER/ca.crt" "$webUIDstCertFolder/ca.crt"
      \cp -f "$WEBUI_SRC_CERT_FOLDER/auth_key.key" "$webUIDstCertFolder/auth_key.key"
    fi

    configureWebUI
    webuiConfRc=$?
    let "piRc=piRc+$webuiConfRc"
  fi

  # Only start the client if all configuration steps went fine
  if [[ $COMPONENT_SRV = "true" ]] || [[ $COMPONENT_WEBUI = "true" ]]
  then
    if [[ $srvDbRc -eq 0 ]] && [[ $webuiConfRc -eq 0 ]]
    then
      startService "${SERVICE_CLIENT[*]}"
      let "piRc=piRc+$?"
    fi
  fi

  if [[ $COMPONENT_WEBUI = "true" ]] && [[ $webuiConfRc -eq 0 ]]
  then
    startService "${SERVICE_WEBUI[*]}"
    let "piRc=piRc+$?"
  fi

  if [[ $piRc -ne 0 ]]
  then
    fnRc=1
  else
    fnRc=0
  fi

  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

configureWebUI()
{
  logFnBegin "${FUNCNAME[0]}"
  fnRc=0

  if [[ $COMPONENT_SRV = "false" ]]
  then
    LD_LIBRARY_PATH="$LD_LIBRARY_PATH":"$DEF_WEBUI_BIN_ROOT"
    export LD_LIBRARY_PATH
  fi

  dbHost=$DB_HOSTNAME
  dbUser=$DB_CONN_USER
  dbPwd=$DB_CONN_PWD
  dbPort=$DB_PORT
  if [[ $COMPONENT_WR = "true" && $COMPONENT_SRV = "false" ]]
  then
    dbHost=$DB_WEBUI_HOSTNAME
    dbUser=$DB_WEBUI_ADMIN_USER
    dbPwd=$DB_WEBUI_PWD
    dbPort=$DB_WEBUI_PORT
  fi

  # The command below mimic what actually does the fixlet. The 'dbInstance' parameter is not used by the fixlet when installing on linux since it is something that is dedicated to SQL Server.
  runCmd="$DEF_WEBUI_BIN_ROOT/BESWebUI --configure --hostname=\"$dbHost\" --domain=\"\" --user=\"$dbUser\" --password=\"$dbPwd\" --instance=\"\" --port=$dbPort --directory=\"$DEF_WEBUI_ROOT/WebUI\""

  toLogCmd="$runCmd"
  toLogCmd=$( echo $toLogCmd | sed "s|-password=\"$DB_CONN_PWD\"|-password=\"********\"|g" )
  writeMsg log "$toLogCmd"

  # execute command, log the output and show the error stream
  eval $runCmd >> $DEF_BES_LOG_FILE 2>&1
  confRc=$?
  if [[ $confRc -ne 0 ]]
  then
    fnRc=1
  else
    fnRc=0
  fi

  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

copyInstaller()
{
  logFnBegin "${FUNCNAME[0]}"
  sourceFile=$1
  destFile=$2
  destPath=$3

  cpInstRc=0
  mkdir -p "$destPath" 2>> $DEF_BES_LOG_FILE
  let "cpInstRc=cpInstRc+$?"
  \cp -f "$DEF_BES_REPOS_FOLDER/$sourceFile" "$destPath/$destFile" 2>> $DEF_BES_LOG_FILE
  let "cpInstRc=cpInstRc+$?"
  \cp -f "$DEF_BES_ETC/$DEF_BES_ACTIONSITE_FILE" "$destPath/$DEF_BES_ACTIONSITE_FILE" 2>> $DEF_BES_LOG_FILE
  let "cpInstRc=cpInstRc+$?"
  if [[ $cpInstRc -ne 0 ]]
  then
    writeMsg both "`nls_replace 'TEM0083E' \"$destPath\"`"
  else
    writeMsg log "Folder $destPath successful populated ..."
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo $cpInstRc
}

cleanInstallerDir()
{
  logFnBegin "${FUNCNAME[0]}"
  destPath=$1
  rmInstRc=0
  mkdir -p "$destPath" 2>> $DEF_BES_LOG_FILE
  let "rmInstRc=rmInstRc+$?"
  \rm -f "$destPath"/*  2>> $DEF_BES_LOG_FILE
  let "rmInstRc=rmInstRc+$?"
  if [[ $rmInstRc -ne 0 ]]
  then
    writeMsg log "Error cleaning  $destPath "
  else
    writeMsg log "Folder $destPath successfully cleaned ..."
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo $rmInstRc
}

populateBESInstallers()
{
  logFnBegin "${FUNCNAME[0]}"
  cpInstRc=0
  fnRc=0

  consoleInstDir="$INSTALLERS_DIR/Console"
  let cpInstRc=cpInstRc+$(cleanInstallerDir "$consoleInstDir")
  winConsoleSetup=`ls "$DEF_BES_REPOS_FOLDER" | grep "BigFix-BES-Console"`
  let cpInstRc=cpInstRc+$(copyInstaller $winConsoleSetup setup.exe "$consoleInstDir")

  agentInstDir="$INSTALLERS_DIR/Client"
  let cpInstRc=cpInstRc+$(cleanInstallerDir "$agentInstDir")
  winClientSetup=`ls "$DEF_BES_REPOS_FOLDER" | grep "BigFix-BES-Client"`
  let cpInstRc=cpInstRc+$(copyInstaller $winClientSetup $winClientSetup "$agentInstDir")
  agentInstDir="$INSTALLERS_DIR/Client"
  let cpInstRc=cpInstRc+$(copyInstaller $RPM_AGT_PKG $RPM_AGT_PKG "$agentInstDir")

  if [[ $cpInstRc -ne 0 ]]
  then
    fnRc=1
  else
    fnRc=0
  fi

  logFnEnd "${FUNCNAME[0]}"
  return $fnRc
}

collectLicenseInput()
{
  logFnBegin "${FUNCNAME[0]}"
  getAuthFile

  getServerDnsName

  getSigningKeyPwd

  selectKeySize

  chooseLicFolder
  logFnEnd "${FUNCNAME[0]}"
}

collectCredentialInput()
{
  logFnBegin "${FUNCNAME[0]}"
  getCredentialUserFirstName

  getCredentialUserLastName

  getCredentialEmail

  getCredentialOrgName
  logFnEnd "${FUNCNAME[0]}"
}

collectAdvMastheadInput()
{
  logFnBegin "${FUNCNAME[0]}"
  chooseAdvMasthDefault
  if [[ $ADV_MASTHEAD_DEFAULT = "false" ]]
  then
    chooseServerPort

    selectFipsCompliants

    selectGatherInterval

    chooseInitialLock 
    if [[ $INITIAL_LOCK = "1" ]]
    then
      chooseLockDuration
    fi

    chooseLockController

    enableLockExemptions
    if [[ $ENABLE_LOCK_EXEMPT = "true" ]]
    then
      specifyExceptionURL
    fi

    selectArchiveAllowUTF8

  else
    BES_SERVER_PORT=$DEF_BES_SERVER_PORT
    WEBUI_APPSERVER_PORT=$DEF_WEBUI_APPSERVER_PORT
    ENABLE_FIPS=${ALLOWED_BOOLEAN[1]}
    BES_GATHER_INTERVAL=${ALLOWED_INTERVAL[5]}
    INITIAL_LOCK=${ALLOWED_INIT_LOCK[2]}
    LOCK_CONTROLLER=${ALLOWED_LOCK_CONTROLLER[0]}
    ENABLE_LOCK_EXEMPT=${ALLOWED_BOOLEAN[1]}
    ENABLE_ARCHIVE_UTF8=${ALLOWED_BOOLEAN[0]}
  fi
  logFnEnd "${FUNCNAME[0]}"
}

collectAdvProxyInput()
{
  logFnBegin "${FUNCNAME[0]}"
  chooseAdvProxyDefault
  if [[ $ADV_PROXY_DEFAULT = "false" ]]
  then

	specifyProxyUser
    if [[ $PROXY_USER != "" ]]
    then
      specifyProxyPwd
    else
      PROXY_PWD=""
    fi

	specifyProxyMeth 

    specifyProxyExceptionList

    specifyProxySecureTunnel

    specifyProxyDownStreamNot
  else
    PROXY_DOWN=""
    PROXY_SECTUNNEL=""
    PROXY_METH=""
    PROXY_USER=""
    PROXY_PWD=""
    PROXY_EXLIST=""
  fi
  logFnEnd "${FUNCNAME[0]}"
}

installFromAuthFile()
{
  logFnBegin "${FUNCNAME[0]}"
  afRc=0
  collectLicenseInput
  submitInternetLicReq
  if [[ $SUBMIT_LIC_REQUEST = "yes" ]]
  then
    specifyEncoding
    collectAdvMastheadInput
    runBesAdmin "-processauthfile"
    let "afRc=afRc+$?"
    BES_LICENSE_PVK="$BES_LIC_FOLDER$DEF_BES_LICENSE_PVK"
    [[ $afRc -eq 0 ]] && renameAuthFile
  else
    runBesAdmin "-processauthfile"
    let "afRc=afRc+$?"
    if [[ $afRc -ne 0 ]]
    then
       logFnEnd "${FUNCNAME[0]}"
       return $afRc
    fi
    BES_LICENSE_PVK="$BES_LIC_FOLDER$DEF_BES_LICENSE_PVK"
    renameAuthFile
    continueFromCert
    if [[ $CONTINUE_FROM_CRT = "yes" ]]
    then
      getLicCertificateFile

      getSigningKey

      specifyEncoding
      collectAdvMastheadInput
      runBesAdmin "-processcertificate"
      let "afRc=afRc+$?"
    else
      generateRespFile
      writeMsg both "`nls_replace 'TEM0029I' \"$BES_LIC_FOLDER$DEF_BES_REQUEST\"`"
      exit 0
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $afRc
}

installFromProdLic()
{
  logFnBegin "${FUNCNAME[0]}"
  plRc=0

  getLicCertificateFile

  getSigningKey

  getSigningKeyPwd

  specifyEncoding

  collectAdvMastheadInput

  chooseLicFolder

  runBesAdmin "-processcertificate"
  let "plRc=plRc+$?"
  logFnEnd "${FUNCNAME[0]}"
  return $plRc
}

freshInstall()
{
  logFnBegin "${FUNCNAME[0]}"
  fiRc=0
  ##Welcome to the installation of $PRODUCT_NAME $PRODUCT_VERSION
  writeMsg both "`nls_replace 'WelcomeDesc' \"$PRODUCT_NAME\" \"$PRODUCT_VERSION\"`"

  checkAllCompsInstalled

  ##Validate parameters specified in the response file
  basicVariableValidation

  checkOsPrereqs

  selectInstallType

  licenseAgreement
  if [[ $LA_ACCEPT = "false" ]]
  then
    writeMsg both "`nls_replace 'TEM0013W'`"
    exit 1
  fi

  if [[ $IS_EVALUATION = "true" ]]
  then
    installStartEval
  else
    installStart
    collectWRUserData
    ##Collect Database Input Parameter
    collectDatabaseInput
  fi

  [[ $DB_TARGET = "db2" ]] && addDb2OdbcDriverIfNeeded

  generateRespFile

  if [[ $COMPONENT_SRV = "true" ]] || [[ $COMPONENT_WR = "true" ]]
  then
    createDatabases
  fi

  if [[ $COMPONENT_SRV = "true" ]] || [[ $COMPONENT_WEBUI = "true" ]]
  then
    installRpm "$DEF_RPM_AGT_PREFIX"
    checkFatalerror $?

    copyMasthead "$DEF_RPM_AGT_PREFIX"
    let "fiRc=fiRc+$?"
  fi

  if [[ $COMPONENT_SRV = "true" ]]
  then
    installRpm "$DEF_RPM_SRV_PREFIX"
    checkFatalerror $?

    if [[ $DEF_LIC_ROOT != "" ]]; then
      \cp -rf "$DEF_LIC_ROOT"/* "$DEF_BES_ROOT"
    fi

    if [[ $BES_WWW_FOLDER != "" ]]
    then
      moveFolders "$DEF_BES_ROOT" "$BES_WWW_FOLDER" $DEF_BES_WWW_FOLDER
    fi

    copyMasthead "$DEF_RPM_SRV_PREFIX"
    let "fiRc=fiRc+$?"

  fi

  if [[ $COMPONENT_WR = "true" ]]
  then

    installRpm "$DEF_RPM_WR_PREFIX"
    checkFatalerror $?

    if [[ $DEF_LIC_ROOT != "" ]]; then
      \cp -rf "$DEF_LIC_ROOT"/* "$DEF_WR_ROOT"
    fi

    if [[ $WR_WWW_FOLDER != "" ]]
    then
      moveFolders "$DEF_WR_ROOT" "$WR_WWW_FOLDER" $DEF_WR_WWW_FOLDER
    fi

    copyMasthead "$DEF_RPM_WR_PREFIX"
    let "fiRc=fiRc+$?"

  fi

  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    installRpm "$DEF_RPM_WEBUI_PREFIX"
    checkFatalerror $?
  fi

  if [[ $DEF_LIC_ROOT != "" ]]
  then
    rm -rf "$DEF_LIC_ROOT"
  fi

  #Execute post install steps
  postInstall
  let "fiRc=fiRc+$?"

  logFnEnd "${FUNCNAME[0]}"
  return $fiRc
}

updateConfigKeyList()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1
  searchSection=$2
  sectionName=$3
  keyName=$4
  keyValue=$5
  replaceLine=$6

  configKeyVal=$(extractConfigKeyVal "$configFile" "$searchSection" "$keyName" "false")

  if [[ $configKeyVal = "" ]] || [[ $replaceLine = "true" ]]
  then
    [[ $replaceLine = "true" ]] && updateOperation="replace" || updateOperation="add"
    writeMsg log "Key to ${updateOperation}: $configFile, $sectionName $keyName $keyValue"
    case $configFile in
     "$DEF_WR_CONFIG")
              wrind=`echo ${#CONFIG_SECTION_WR[*]}`
              CONFIG_SECTION_WR[$wrind]=$sectionName
              CONFIG_SEARCH_WR[$wrind]=$searchSection
              CONFIG_KEY_WR[$wrind]="$keyName          = $keyValue"
              CONFIG_REPLACE_LINE_WR[$wrind]=$replaceLine
              ;;
     "$DEF_BES_CONFIG")
              srvind=`echo ${#CONFIG_SECTION_SRV[*]}`
              CONFIG_SECTION_SRV[$srvind]=$sectionName
              CONFIG_SEARCH_SRV[$srvind]=$searchSection
              CONFIG_KEY_SRV[$srvind]="$keyName          = $keyValue"
            ;;
     *)
              clientind=`echo ${#CONFIG_SECTION_CLIENT[*]}`
              CONFIG_SECTION_CLIENT[$clientind]=$sectionName
              CONFIG_SEARCH_CLIENT[$clientind]=$searchSection
              CONFIG_KEY_CLIENT[$clientind]="$keyName          = $keyValue"
            ;;
    esac
  fi
  logFnEnd "${FUNCNAME[0]}"
}

updateClientSetting()
{
  logFnBegin "${FUNCNAME[0]}"
  clientConfigFile=$1
  key=$2
  value=$3

  updateConfigKeyList "$clientConfigFile" "$key" "[Software\BigFix\EnterpriseClient\Settings\Client\\$key]" "value" "$value"
  logFnEnd "${FUNCNAME[0]}"
}

upgradeConfigFile()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1

  if [[ $configFile = "$DEF_BES_CONFIG" ]]
  then 
    cpuNumber=`cat /proc/cpuinfo | grep -c processor`
    if [[ cpuNumber -ge 10 ]]
    then
        PARALLELISM_ENABLED="1"
        PARALLELISM_ENABLED_FOR_QUERY="1"
    elif [[ cpuNumber -ge 6 ]]
    then
        PARALLELISM_ENABLED="1"
        PARALLELISM_ENABLED_FOR_QUERY="0"
    else
        PARALLELISM_ENABLED="0"
        PARALLELISM_ENABLED_FOR_QUERY="0"
    fi

    updateConfigKeyList "$configFile" "_BESRelay_HTTPServer_LogFilePath" "[Software\BigFix\EnterpriseClient\Settings\Client\_BESRelay_HTTPServer_LogFilePath]" "value" "/var/log/BESRelay.log"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "FastBufferdir" "/var/opt/BESServer/FillDBData/FastBufferDir"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "NumberOfDBUpdatingThreadsForQuery" "3"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "NumberOfParsingThreadsForQuery" "3"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "ParallelismEnabledForQuery" "$PARALLELISM_ENABLED_FOR_QUERY"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "NumberOfDBUpdatingThreads" "3"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "NumberOfParsingThreads" "3"
    updateConfigKeyList "$configFile" "FillDB]" "[Software\BigFix\Enterprise Server\FillDB]" "ParallelismEnabled" "$PARALLELISM_ENABLED"
  else
    updateConfigKeyList "$configFile" "PDFExe" "[Software\BigFix\Enterprise Server\BESReports]" "PDFExe" "/var/opt/BESWebReportsServer/BESReportsData/BESExe/generatepdf.sh" "true"

    updateConfigKeyList "$configFile" "BESReports]" "[Software\BigFix\Enterprise Server\BESReports]" "PDFEnable" "1"
  fi
  writeUpdConfigFile $configFile
  logFnEnd "${FUNCNAME[0]}"
}

writeUpdConfigFile()
{
  logFnBegin "${FUNCNAME[0]}"
  configFile=$1
  maxInd=0
  currInd=0
  searchStr=""
  section=""
  key=""
  replace=""

  if [[ $configFile = "$DEF_BES_CONFIG" ]]
  then
    maxInd=`echo ${#CONFIG_SECTION_SRV[*]}`
  elif [[ $configFile = "$DEF_WR_CONFIG" ]]
  then
    maxInd=`echo ${#CONFIG_SECTION_WR[*]}`
  else
    maxInd=`echo ${#CONFIG_SECTION_CLIENT[*]}`
  fi

  if [[ $maxInd -gt 0 ]]
  then
    mv -f "$configFile" "$configFile"_bkp 2>> $DEF_BES_LOG_FILE
    currConfigFile="$configFile"_bkp
    while [[ $currInd -lt $maxInd ]]
    do
      if [[ $configFile = "$DEF_BES_CONFIG" ]]
      then
        searchStr=${CONFIG_SEARCH_SRV[$currInd]}
        section=${CONFIG_SECTION_SRV[$currInd]}
        key=${CONFIG_KEY_SRV[$currInd]}
      elif [[ $configFile = "$DEF_WR_CONFIG" ]]
      then
        searchStr=${CONFIG_SEARCH_WR[$currInd]}
        section=${CONFIG_SECTION_WR[$currInd]}
        key=${CONFIG_KEY_WR[$currInd]}
        replace=${CONFIG_REPLACE_LINE_WR[$currInd]}
      else
        searchStr=${CONFIG_SEARCH_CLIENT[$currInd]}
        section=${CONFIG_SECTION_CLIENT[$currInd]}
        key=${CONFIG_KEY_CLIENT[$currInd]}
      fi
      cat $currConfigFile | grep "$searchStr" > /dev/null
      if [[ $? -eq 0 ]]
      then
        if [[ $replace = "true" ]]
        then
          sed "/$searchStr/c$key" "$currConfigFile" > "$configFile"_$currInd
        else
          sed "/$searchStr/a$key" "$currConfigFile" > "$configFile"_$currInd
        fi
      else
        cat "$currConfigFile" > "$configFile"_$currInd
        echo "$section" >> "$configFile"_$currInd
        echo "$key" >> "$configFile"_$currInd
      fi
      rm -f "$currConfigFile" 2>> $DEF_BES_LOG_FILE
      currConfigFile="$configFile"_$currInd
      let currInd+=1
    done
    mv -f "$currConfigFile" "$configFile" 2>> $DEF_BES_LOG_FILE
  fi
  logFnEnd "${FUNCNAME[0]}"
}

checkMinimumUpgradeVersion()
{
  logFnBegin "${FUNCNAME[0]}"
  componentRPMPrefix="$1"
  installedBESVersion=`rpm -q --queryformat '%{VERSION}\n' $componentRPMPrefix`
  IFS='.' read oldMajor oldMinor oldPatch oldBuild <<< "$installedBESVersion"
  minVersion="$BES_MINIMUM_UPGRADE_VERSION"
  if [[ $componentRPMPrefix = "$DEF_RPM_WEBUI_PREFIX" ]]
  then
    minVersion="$WEBUI_MINIMUM_UPGRADE_VERSION"
  fi
  IFS='.' read minimumMajor minimumMinor minimumPatch <<< "$minVersion"
  if [[ $oldMajor -gt $minimumMajor || \
    $oldMajor -eq $minimumMajor && $oldMinor -gt $minimumMinor || \
    $oldMajor -eq $minimumMajor && $oldMinor -eq $minimumMinor && $oldPatch -ge $minimumPatch  ]]
  then
    logFnEnd "${FUNCNAME[0]}"
    return 0
  fi
  if [[ $componentRPMPrefix = "$DEF_RPM_WEBUI_PREFIX" ]]
  then
    writeMsg both "`nls_replace 'TEM0173E' \"$installedBESVersion\" \"$minVersion\"`"
  else
    writeMsg both "`nls_replace 'TEM0149E' \"$installedBESVersion\" \"$minVersion\"`"
  fi
  logFnEnd "${FUNCNAME[0]}"
  exit 1
}

percentdecode()
{
  logFnBegin "${FUNCNAME[0]}"
  plus_sanitized=${1//+/ }
  logFnEnd "${FUNCNAME[0]}"
  printf '%b' "${plus_sanitized//%/\\x}"
}

ensureCredentials()
{
  logFnBegin "${FUNCNAME[0]}"
  runBesAdmin "-ensurecredentials"
  ret=$?
  if [[ $ret -ne 0 ]]
  then
    BES_LICENSE_PVK_PWD=""
  fi
  logFnEnd "${FUNCNAME[0]}"
  return $ret
}

preUpgradeCheck()
{
  logFnBegin "${FUNCNAME[0]}"
  # pre-upgrade check for non-ASCII-named site files
  BESClientActionMastheadPath="$DEF_BES_ETC/$DEF_BES_ACTIONSITE_FILE"
  export BESClientActionMastheadPath

  DB2INSTANCE="$DB2_INSTANCE_NAME"
  export DB2INSTANCE

  LD_LIBRARY_PATH=$DEF_BES_REPOS_FOLDER:$LD_LIBRARY_PATH
  export LD_LIBRARY_PATH

  RUN_CMD="$DEF_BES_REPOS_FOLDER/BESAdmin -preupgrade"
  writeMsg log "$RUN_CMD"

  PRE_UPGRADE_OUTPUT="$(eval $RUN_CMD 2>&1)"
  PRE_UPGRADE_RETURN_CODE=$?

  writeMsg log "$PRE_UPGRADE_OUTPUT"

  if [[ $PRE_UPGRADE_RETURN_CODE -ne 0 ]]
  then
    writeMsg both "$PRE_UPGRADE_OUTPUT"
    exit $PRE_UPGRADE_RETURN_CODE
  fi
  logFnEnd "${FUNCNAME[0]}"
}

performAutomaticBackupIfEnabled()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $DB_TARGET = "mssql" ]]
  then
    logFnEnd "${FUNCNAME[0]}"
    return 0
  fi

  if [[ $COMPONENT_SRV = "true" ]]
  then
    BES_LIBPATH=$DEF_BES_REPOS_FOLDER
    BESClientActionMastheadPath="$DEF_BES_ETC/$DEF_BES_ACTIONSITE_FILE"

    export BES_LIBPATH
    export BESClientActionMastheadPath

    $DEF_BES_REPOS_FOLDER/BESAdmin "-backup" "-test" &> /dev/null
    returnCode=$?

    if [[ $returnCode -eq 0 ]]
    then
      writeMsg both "$2"
      $DEF_BES_REPOS_FOLDER/BESAdmin "-backup" -db2ClientUsername:\"$DB_ADMIN_USER\" "$1" >>  $DEF_BES_LOG_FILE 2>&1
      lastrc=$?
      logFnEnd "${FUNCNAME[0]}"
      return $lastrc
    fi
  fi

  logFnEnd "${FUNCNAME[0]}"
  return 0
}

addDb2OdbcDriverIfNeeded()
{
  logFnBegin "${FUNCNAME[0]}"
  if [[ $COMPONENT_SRV = "true" || $COMPONENT_WR = "true" ]]
  then
    db2InstanceHomePath=$(echo "$DB2_LIB_PATH" | cut -d : -f 1)
    odbcinst -q -d -n DB2 &> /dev/null
    returnCode=$?
    if [[ $returnCode -ne 0 ]]
    then
      cat << EOF | odbcinst -i -d -r &> /dev/null
[DB2]
Description = DB2 ODBC Driver
Driver = $db2InstanceHomePath/libdb2o.so
FileUsage = 1
EOF
      returnCode=$?
      if [[ $returnCode -ne 0 ]]
      then
        writeMsg both "`nls_replace 'TEM0182I'`"
        exit 1
      fi
      writeMsg both "`nls_replace 'TEM0182I'`"
    else
      writeMsg both "`nls_replace 'TEM0183I'`"
    fi
  fi
  logFnEnd "${FUNCNAME[0]}"
}

fixBesCommonFilesPermissionBits()
{
  logFnBegin "${FUNCNAME[0]}"
  chmod g-rwx,o-rwx \
    /var/opt/BESCommon \
    /var/opt/BESCommon/BESComm.id \
    /var/opt/BESCommon/BESDeploy.id \
    /var/opt/BESCommon/BESLib.id \
    /var/opt/BESCommon/BESShared.id \
    /var/opt/BESCommon/BESHostname.id \
    /var/opt/BESCommon/.HostIDAccess.read \
    /var/opt/BESCommon/.HostIDAccess.write \
    /var/opt/BESCommon/.IDAccess.read \
    /var/opt/BESCommon/.IDAccess.write
  logFnEnd "${FUNCNAME[0]}"
}

upgradeInstall()
{
  logFnBegin "${FUNCNAME[0]}"
  uiRc=0
  writeMsg both "`nls_replace 'WelcomeUpgDesc' \"$PRODUCT_NAME\" \"$PRODUCT_VERSION\"`"
  srvRpmRc=0
  agtRpmRc=0
  wrRpmRc=0
  webuiRpmRc=0

  basicVariableValidation
  if [[ $DB_TARGET = "db2" && "$BES_LICENSE_PVK" != "" && "$BES_LICENSE_PVK_PWD" != "" ]]
  then
    DB_ADMIN_USER=$(extractKeyVal "$DEF_BES_ROOT/bes.info" "DB2_ADMIN_USER")
    updateDb2PathVariables
  fi

  identifyInstalledComps

  if [[ $COMPONENT_SRV != "true" && $COMPONENT_WR != "true" && $COMPONENT_WEBUI != "true" ]]
  then
    writeMsg both "`nls_replace 'TEM0128W'`"
    exit 0
  fi

  checkOsPrereqs

  if [[ $RUN_AS_FIXLET = "true" ]]
  then
    ASK_PVK_CREDENTIALS=false
    BES_RESTART=false
    BES_UPGRADE_CLIENT=false
  fi

  if [[ $COMPONENT_SRV = "true" ]]
  then
    checkMinimumUpgradeVersion "$DEF_RPM_SRV_PREFIX"
  fi

  if [[ $COMPONENT_WR = "true" ]]
  then
    checkMinimumUpgradeVersion "$DEF_RPM_WR_PREFIX"
  fi

  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    checkMinimumUpgradeVersion "$DEF_RPM_WEBUI_PREFIX"
  fi

  if [[ $COMPONENT_SRV = "true" ]]
  then
    if [[ $DB_TARGET = "db2" ]]
    then
      DB_ADMIN_USER=$(extractKeyVal "$DEF_BES_ROOT/bes.info" "DB2_ADMIN_USER")
      updateDb2PathVariables

      [ "$DB2_LIB_PATH" ] || checkFatalerror "1"

      DB2_INSTANCE_NAME=$(extractKeyVal "$DEF_BES_ROOT/bes.info" "DB2_INSTANCE" "false")
      [ "$DB2_INSTANCE_NAME" ] || DB2_INSTANCE_NAME=$(extractKeyVal "$SERVICE_FOLDER/${SERVICE_SERVER[0]}" "DB2INSTANCE" "false")
      [ "$DB2_INSTANCE_NAME" ] || DB2_INSTANCE_NAME=$DB_ADMIN_USER

      addDb2OdbcDriverIfNeeded
    fi

    preUpgradeCheck

    BES_WWW_FOLDER=$(percentdecode $(extractConfigKeyVal "$DEF_BES_CONFIG" "_BESRelay_HTTPServer_ServerRootPath" "value" "true"))
    [ "$BES_WWW_FOLDER" ] || checkFatalerror "1"

    [[ $ASK_PVK_CREDENTIALS = "false" ]] || ASK_PVK_CREDENTIALS=$(updateMasthead)
    if [[ $ASK_PVK_CREDENTIALS = "true" ]]
    then
      while :
      do
        collectPvkCredentials
        ensureCredentials
        if [[ $? -eq 0 ]]
        then
          break
        fi
      done
    else
      if [[ $BES_LICENSE_PVK != "" || $BES_LICENSE_PVK_PWD != "" ]]
      then
        writeMsg both "`nls_replace 'TEM0178W'`"
      fi
    fi

    if [[ $COMPONENT_WEBUI = "true" ]]
    then
      writeMsg both "`nls_replace 'TEM0174I'`"
      stopService "${SERVICE_WEBUI[*]}"
    fi

    writeMsg both "`nls_replace 'TEM0069I'`"

    stopService "${SERVICE_GATHERDB[*]}"
    stopService "${SERVICE_FILLDB[*]}"
    stopService "${SERVICE_SERVER[*]}"

    databaseName="-BFENT"
    performAutomaticBackupIfEnabled $databaseName "`nls_replace 'TEM0158I'`"
    returnCode=$?

    if [[ $returnCode -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0157E'`"
      exit 1
    fi

    upgradeRpm "$DEF_RPM_SRV_PREFIX"
    srvRpmRc=$?

    if [[ $srvRpmRc -eq 0 ]]
    then
      if [[ $DB_TARGET = "db2" ]]
      then
        resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_SERVER[0]}"
        let "srvRpmRc=srvRpmRc+$?"
        resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_FILLDB[0]}"
        let "srvRpmRc=srvRpmRc+$?"
        resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_GATHERDB[0]}"
        let "srvRpmRc=srvRpmRc+$?"
      fi
      daemonReload

      copyFolderContent "$DEF_BES_ROOT$DEF_BES_WWW_FOLDER" "$BES_WWW_FOLDER" "$DEF_BES_WWW_FOLDER"
      let "srvRpmRc=srvRpmRc+$?"

      getRpmPkgName "$DEF_RPM_AGT_PREFIX"

      populateBESInstallers
      let "srvRpmRc=srvRpmRc+$?"

      writeBesInfoFile "$DEF_BES_ROOT"

      if [[ $DB_TARGET = "db2" ]]
      then
        resolveScriptTag "<DB2INSTANCE>" "$DB2_INSTANCE_NAME" "$DEF_BES_REPOS_FOLDER/BESAdmin.sh" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
        let "srvRpmRc=srvRpmRc+$?"
        resolveScriptTag "<DB2_ADMIN_USER>" "$DB_ADMIN_USER" "$DEF_BES_BIN_ROOT/BESAdmin.sh"
        let "piRc=piRc+$?"

        resolveScriptTag "<DB2INSTANCE>" "$DB2_INSTANCE_NAME" "$DEF_BES_REPOS_FOLDER/Airgap.sh" "$DEF_BES_BIN_ROOT/Airgap.sh"
        let "srvRpmRc=srvRpmRc+$?"
      fi

      upgradeConfigFile "$DEF_BES_CONFIG"

      if [[ $DB_TARGET = "db2" ]]
      then
        setRegistryValuesForDb2Locking
      fi

      upgradeSrvDatabase
      let "srvRpmRc=srvRpmRc+$?"

      if [[ $srvRpmRc -eq 0 ]]
      then
        performAutomaticBackupIfEnabled $databaseName "`nls_replace 'TEM0159I'`"
        returnCode=$?

        if [[ $returnCode -ne 0 ]]
        then
          writeMsg both "`nls_replace 'TEM0156W'`"
        fi
      fi
    fi
    if [[ $srvRpmRc -eq 0 ]]
    then
      ind=`echo ${#serviceListProc[*]}`
      serviceListProc[$ind]=${SERVICE_SERVER[*]}
      let ind+=1
      serviceListProc[$ind]=${SERVICE_FILLDB[*]}
      let ind+=1
      serviceListProc[$ind]=${SERVICE_GATHERDB[*]}
    fi
    let "uiRc=uiRc+$srvRpmRc"

    if [[ $BES_UPGRADE_CLIENT != "false" ]]
    then
      writeMsg both "`nls_replace 'TEM0084I'`"
      stopService "${SERVICE_CLIENT[*]}"

      isRpmInstalled "$DEF_RPM_AGT_PREFIX"
      lastrc=$?
      if [[ $lastrc -ne 0 ]]
      then
        installRpm "$DEF_RPM_AGT_PREFIX" "-upgrade"
        agtRpmRc=$?
      fi
      if [[ $agtRpmRc -eq 0 ]]
      then
        ind=`echo ${#serviceListProc[*]}`
        serviceListProc[$ind]=${SERVICE_CLIENT[*]}
      fi
      let "uiRc=uiRc+$agtRpmRc"
    fi
  fi

  if [[ $COMPONENT_WR = "true" ]]
  then
    writeMsg both "`nls_replace 'TEM0070I'`"
    stopService "${SERVICE_WEBREPORT[*]}"

    if [[ $DB_TARGET = "db2" ]]
    then
      if [[ $DB_ADMIN_USER = "" ]]
      then
        if [[ -f "$DEF_WR_ROOT/bes.info" ]]
        then
          DB_ADMIN_USER=$(extractKeyVal "$DEF_WR_ROOT/bes.info" "DB2_ADMIN_USER")
        fi
        updateDb2PathVariables

        [ "$DB2_LIB_PATH" ] || checkFatalerror "1"
      fi

      if [[ $DB2_INSTANCE_NAME = "" ]]
      then
        if [[ -f "$DEF_WR_ROOT/bes.info" ]]
        then
          DB2_INSTANCE_NAME=$(extractKeyVal "$DEF_WR_ROOT/bes.info" "DB2_INSTANCE" "false")
        fi
        [ "$DB2_INSTANCE_NAME" ] || DB2_INSTANCE_NAME=$(extractKeyVal "$SERVICE_FOLDER/${SERVICE_WEBREPORT[0]}" "DB2INSTANCE" "false")
        [ "$DB2_INSTANCE_NAME" ] || DB2_INSTANCE_NAME=$DB_ADMIN_USER
      fi

      addDb2OdbcDriverIfNeeded
    fi

    WR_WWW_FOLDER=$(percentdecode $(extractConfigKeyVal "$DEF_WR_CONFIG" "_WebReports_HTTPServer_ServerRootPath" "value" "true"))
    [ "$WR_WWW_FOLDER" ] || checkFatalerror "1"

    wrObfFile="$DEF_WR_ROOT/beswebreports.obf"
    DB_CONN_PWD=$(extractConfigKeyVal "$wrObfFile" "BESServer_Database_Password" "value" "true")
    [ "$DB_CONN_PWD" ] || checkFatalerror "1"

    databaseName="-$DEF_WR_DB_NAME"
    performAutomaticBackupIfEnabled $databaseName "`nls_replace 'TEM0158I'`"
    returnCode=$?

    if [[ $returnCode -ne 0 ]]
    then
      writeMsg both "`nls_replace 'TEM0157E'`"
      exit 1
    fi

    # during 9.5.10 we removed the BESEmailer, but we should preserve whoever is happy with it
    # we can't handle with RPM since seems to be removed because it is found only on the old package
    if [[ -f "/var/opt/BESWebReportsServer/BESReportsData/BESExe/BESEmailer" ]]
    then
      mv /var/opt/BESWebReportsServer/BESReportsData/BESExe/BESEmailer /var/opt/BESWebReportsServer/BESReportsData/BESExe/BESEmailer.bak
    fi

    upgradeRpm "$DEF_RPM_WR_PREFIX"

    if [[ -f "/var/opt/BESWebReportsServer/BESReportsData/BESExe/BESEmailer.bak" ]]
    then
      mv /var/opt/BESWebReportsServer/BESReportsData/BESExe/BESEmailer.bak /var/opt/BESWebReportsServer/BESReportsData/BESExe/BESEmailer
    fi

    wrRpmRc=$?
    if [[ $wrRpmRc -eq 0 ]]
    then
      if [[ $DB_TARGET = "db2" ]]
      then
        resolveScriptTag "DB2INSTANCE=db2inst1" "DB2INSTANCE=$DB2_INSTANCE_NAME" "$SERVICE_FOLDER/${SERVICE_WEBREPORT[0]}"
        let "wrRpmRc=wrRpmRc+$?"
      fi
      daemonReload

      copyFolderContent "$DEF_WR_ROOT$DEF_WR_WWW_FOLDER" "$WR_WWW_FOLDER" "$DEF_WR_WWW_FOLDER"
      let "wrRpmRc=wrRpmRc+$?"

      writeBesInfoFile "$DEF_WR_ROOT"

      upgradeConfigFile "$DEF_WR_CONFIG"

      fixBesCommonFilesPermissionBits

      if [[ -f "/var/opt/BESWebReportsServer/.user" ]]
      then
        WR_NONROOT_USER_NAME=`cat "/var/opt/BESWebReportsServer/.user"`;
        changePermissionsForNonRootUser
      fi

      initWRDB "-upgrade"
      let "wrRpmRc=wrRpmRc+$?"

      if [[ $wrRpmRc -eq 0 ]]
      then
        performAutomaticBackupIfEnabled $databaseName "`nls_replace 'TEM0159I'`"
        returnCode=$?

        if [[ $returnCode -ne 0 ]]
        then
          writeMsg both "`nls_replace 'TEM0156W'`"
        fi
      fi
    fi
    if [[ $wrRpmRc -eq 0 ]]
    then
      ind=`echo ${#serviceListProc[*]}`
      serviceListProc[$ind]=${SERVICE_WEBREPORT[*]}
    fi

    let "uiRc=uiRc+$wrRpmRc"
  fi

  if [[ $COMPONENT_SRV = "true" ]]
  then
    firewall-cmd --state 2> /dev/null 1> /dev/null
    if [[ $? -eq 0 ]]
    then
      FIREWALL_TYPE=${ALLOWED_FIREWALL_TYPE[1]}
    else
      FIREWALL_TYPE=${ALLOWED_FIREWALL_TYPE[0]}
    fi

    confFw="true"
    if [[ $FIREWALL_TYPE = ${ALLOWED_FIREWALL_TYPE[0]} ]]
    then
      service iptables status > /dev/null
      if [[ $? -ne 0 ]]
      then
        confFw="false"
        writeMsg log "Warning: Unable to retrieve the status of iptables"
      fi
    fi

    if [[ $confFw = "true" ]]
    then
      BES_MASTHEAD_FILE=/etc/opt/BESServer/actionsite.afxm
      getMastheadHostAndPort
      let WEBUI_APPSERVER_PORT=MASTHEAD_PORT+4
      configureFirewallPort $WEBUI_APPSERVER_PORT "tcp"
      if [[ $? -eq 0 ]]
      then
        if [[ $FIREWALL_TYPE = ${ALLOWED_FIREWALL_TYPE[0]} ]]
        then
          service iptables save > /dev/null
          if [[ $? -ne 0 ]]
          then
            writeMsg log "Warning: Unable to save iptables rules"
          fi
        fi
      else
        writeMsg log "Warning: Unable to configure local OS Firewall"
      fi
    fi
  fi

  if [[ $COMPONENT_WEBUI = "true" ]]
  then
    if [[ $COMPONENT_SRV != "true" && $BES_UPGRADE_CLIENT != "false" ]]
    then
      writeMsg both "`nls_replace 'TEM0084I'`"
      stopService "${SERVICE_CLIENT[*]}"

      isRpmInstalled "$DEF_RPM_AGT_PREFIX"
      lastrc=$?
      if [[ $lastrc -ne 0 ]]
      then
        installRpm "$DEF_RPM_AGT_PREFIX" "-upgrade"
        agtRpmRc=$?
      fi
      if [[ $agtRpmRc -eq 0 ]]
      then
        ind=`echo ${#serviceListProc[*]}`
        serviceListProc[$ind]=${SERVICE_CLIENT[*]}
      fi
      let "uiRc=uiRc+$agtRpmRc"
    fi

    # if we did not upgrade the server, we need to stop the WebUI service
    if [[ $COMPONENT_SRV != "true" ]]
    then
      writeMsg both "`nls_replace 'TEM0174I'`"
      stopService "${SERVICE_WEBUI[*]}"
    fi

    upgradeRpm "$DEF_RPM_WEBUI_PREFIX"

    if [[ $webuiRpmRc -eq 0 ]]
    then
      ind=`echo ${#serviceListProc[*]}`
      serviceListProc[$ind]=${SERVICE_WEBUI[*]}
    fi

    let "uiRc=uiRc+$webuiRpmRc"
  fi

  maxInd=`echo ${#serviceListProc[*]}`
  if [[ $BES_RESTART = "false" ]]
  then  
    [[ $maxInd -eq 0 ]] || writeMsg both "`nls_replace 'TEM0101I'`"
  fi

  currInd=0
  while [[ $currInd -lt $maxInd ]]
  do
    if [[ $BES_RESTART = "false" ]]
    then
      svcs=(${serviceListProc[$currInd]})
      writeMsg both $'\t'"- \"${svcs[0]}\""
    else
      startService "${serviceListProc[$currInd]}"
    fi
    let currInd+=1
  done

  logFnEnd "${FUNCNAME[0]}"
  return $uiRc
}

collectAndTestProxyInput()
{
logFnBegin "${FUNCNAME[0]}"
while :
do
  chooseUseProxy
  if [[ $USE_PROXY = "true" ]]
  then
	specifyProxyHost
	chooseProxyPort
	collectAdvProxyInput
	chooseTestProxy
	if [[ $TEST_PROXY != "no" ]]
	then
		runBesAdmin  "-testproxyconnection"
		fnRc=$?
		if [[ $fnRc -ne 0 ]]  
		then
			if [[ "$IS_SILENT" = "true" ]]
			then
				checkFatalerror $fnRc
			else
				chooseAgainProxyInput
				if [[ $REINPUT_PROXY = "yes" ]]
				then
					resetProxyInputAll
				else
					break
				fi
			fi
		else
			break	
		fi
	else
		break
	fi
  else
	resetProxyInput
	break
  fi
done	  
logFnEnd "${FUNCNAME[0]}"
}

resetProxyInputAll()
{
	logFnBegin "${FUNCNAME[0]}"
	resetProxyInput
	USE_PROXY=""
	ADV_PROXY_DEFAULT=""
	TEST_PROXY=""
	REINPUT_PROXY=""
	logFnEnd "${FUNCNAME[0]}"
}

resetProxyInput()
{
	logFnBegin "${FUNCNAME[0]}"
	PROXY_HOST=""
	PROXY_PORT=""
	PROXY_DOWN=""
	PROXY_SECTUNNEL=""
	PROXY_METH=""
	PROXY_USER=""
	PROXY_PWD=""
	PROXY_EXLIST=""
	logFnEnd "${FUNCNAME[0]}"
}

runObfuscatePassword()
{
  logFnBegin "${FUNCNAME[0]}"
  pswd=$1
  tool="$DEF_BES_REPOS_FOLDER/BESAdmin"
  cmd="-obfuscatepassword -password:"
  if [[ $COMPONENT_SRV = "false" && $COMPONENT_WR = "false" ]]
  then
    tool="$DEF_BES_REPOS_FOLDER/BESWebUI"
    cmd="--encrypt "
  fi
  BES_LIBPATH=$DEF_BES_REPOS_FOLDER
  export BES_LIBPATH
  runCmd="$tool $cmd$pswd"
  encrypted=$($runCmd)
  fnRc=$?
  logFnEnd "${FUNCNAME[0]}"
  echo $encrypted
  return $fnRc
}

changePermissionsForNonRootUser()
{
  logFnBegin "${FUNCNAME[0]}"
  writeMsg log "Changing ownership to Web Reports folders in order to run the Web Reports service as '$WR_NONROOT_USER_NAME'."
  primaryGroup=$(id -gn $WR_NONROOT_USER_NAME)

  chown -R -L $WR_NONROOT_USER_NAME:$primaryGroup /var/opt/BESWebReportsServer
  chown -R -L $WR_NONROOT_USER_NAME:$primaryGroup $WR_WWW_FOLDER
  chown -R -L $WR_NONROOT_USER_NAME:$primaryGroup /opt/BESWebReportsServer
  chown -R -L $WR_NONROOT_USER_NAME:$primaryGroup $DEF_WR_ETC

  # This way the WR_NONROOT_USER_NAME would be able to restart beswebreports
  # passwordless which is required for self-restart due for example to adding a new datasource.
  # This will allow only to restart it but it would not be able to only stop
  # it, so we should be safe here.
  writeMsg log "Allow user '$WR_NONROOT_USER_NAME' to restart the Web Reports service."
  echo "$WR_NONROOT_USER_NAME ALL= NOPASSWD: /etc/init.d/beswebreports restart" > /etc/sudoers.d/beswebreports

  # ACL to '/var/opt/BESCommon' folder and files for non root user are set during the service startup ."

  logFnEnd "${FUNCNAME[0]}"
  echo $WR_NONROOT_USER_NAME > /var/opt/BESWebReportsServer/.user
}

isSqlServerInstalled()
{
  logFnBegin "${FUNCNAME[0]}"
  isInstalled="false"
  if [[ -f "/opt/mssql/bin/sqlservr" ]]
  then
    isInstalled="true"
  fi
  logFnEnd "${FUNCNAME[0]}"
  echo "$isInstalled"
}
