#!/bin/bash
##########################################################
#
#  Copyright (c) 2026, Oracle. All rights reserved
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Name: oracle-database-preinstall-verify
# Description: A script to verify and set Oracle Preinstall settings 
# on Oracle Linux.
#
LANG=C
PWD=$(/usr/bin/readlink "$0")
PWD=$(/usr/bin/dirname "${PWD:-$0}")
BASE_DIR=$(cd "${PWD}" && /bin/pwd)
CUT="/bin/cut"
SED="/bin/sed"

PREINFILE=$(basename "$0" | sed -e 's/-verify$//g')

RUN_PREINSTALL_EXPR=$(echo "$PREINFILE" | sed -e 's/-/_/g' -e 's/\(.*\)/\U\1/')
TEST_LOG_LOC=/var/log/${PREINFILE}/results;
CONFIG_FILE=${BASE_DIR}/${PREINFILE}.conf
PARAMS=${BASE_DIR}/${PREINFILE}.param;
OLD_PARAMS=${TEST_LOG_LOC}/.${PREINFILE}.param;
PRE_PARAM_LOG=${TEST_LOG_LOC}/orakernel.log;
PRE_DATE=$(date "+%b-%d-%Y-%H-%M-%S")
BACKUP_DIR=/var/log/${PREINFILE}/backup/${PRE_DATE}

SYSCTL="/etc/sysctl.conf";
SYSCTL_DIR="/etc/sysctl.d"
SYSCTL_PACKAGE="${SYSCTL_DIR}/99-${PREINFILE}-sysctl.conf"
SYSCTL_DIRS=("${SYSCTL_DIR}" /run/sysctl.d /usr/local/lib/sysctl.d /usr/lib/sysctl.d /lib/sysctl.d)

LARCH=$(/bin/uname -m | $SED 's/^[ \t]*//; s/[ \t]*$//')
LKERNEL=$(/bin/uname -r | $SED 's/^[ \t]*//; s/[ \t]*$//')
#LDISTRO=$(/bin/cat /etc/issue | $SED '/^$/d' | $SED q | $SED 's/Welcome to//g' | $CUT -d"(" -f1 | $SED 's/^[ \t]*//' | $SED 's/[ \t]*$//')
#LDISTRO=$(awk -F"=" '$1=="NAME" {print $2}' /etc/os-release)
LDISTRO=$(awk -F= '$1=="VERSION" { print $2 ;}' /etc/os-release | sed -e 's%"%%g'| awk -F"." '{print $1}')

GRUB2_DIR=/boot/grub2
GRUB_EFI_DIR=/boot/efi/EFI/redhat/
if [ "$LDISTRO" -ge 9 ]; then
   GRUB_EFI_DIR=/boot/grub2
fi
GRUB2_FILE=grub.cfg

LIMITSFILE="/etc/security/limits.d/${PREINFILE}.conf"
SYSCONFIGNET="/etc/sysconfig/network"
SYSCONFIGNETBKP=${SYSCONFIGNET}.orabackup
# /var/lock may point into /run, whose target can be absent during Leapp.
LOCKFILE=/run/lock/subsys/oracle-preinstall.lock

#/bin/cat /proc/cpuinfo | /bin/grep -i "vendor_id" | /bin/grep -i "intel" 1> /dev/null
#lproc=$(grep -i "model name.*:" /proc/cpuinfo | head -1 | awk -F":" '{print $2}' | sed -e 's/^[[:space:]]*//g' | awk -F " " '{print $1}')
lproc=$(lshw -class cpu | grep -i "vendor:" | head -1 | awk -F":" '{print $2}')
echo "$lproc" | grep -i "intel" > /dev/null  2>&1 
if [ "$?" -eq "0" ]; then
  LPROCESSOR=Intel
else
  echo "$lproc" | grep -i "amd"  > /dev/null  2>&1
  if [ $? -eq 0 ]; then
     LPROCESSOR=AMD
  else
     echo "$lproc" | grep -i "qemu"  > /dev/null  2>&1
     if [ $? -eq 0 ]; then
        LPROCESSOR=QEMU
     else
        LPROCESSOR=Generic
     fi
  fi
fi

f_lock ()
{
   mkdir -p -- "${LOCKFILE%/*}" || return 1
   exec 199>"${LOCKFILE}" || return 1
   if ! flock -x 199; then
      exec 199>&-
      return 1
   fi
}

f_unlock ()
{
   flock -u 199
   local status=$?
   # Retain the inode so waiters cannot lock a different replacement file.
   exec 199>&-
   return "${status}"
}

f_checkgrub ()
{
  export GRUB_EFI=0
 
  if [ -d /boot/grub2 ]; then
      export GRUB_VER=2
      BOOTDIR=${GRUB2_DIR}
  fi

  # Check for GRUB2
  BOOTFILE="${GRUB2_DIR}"/"${GRUB2_FILE}"
  BOOTLINK=$(/usr/bin/readlink -e "${BOOTFILE}"  2> /dev/null);
  if [ -f "${GRUB_EFI_DIR}"/"${GRUB2_FILE}" ]; then
     GRUB_EFI=1
     BOOTDIR="${GRUB_EFI_DIR}"
     BOOTFILE="${GRUB_EFI_DIR}"/"${GRUB2_FILE}"
  elif [ ! -z "$BOOTLINK" ]; then
     BOOTFILE="$BOOTLINK"
  else
     echo "Bootfile ${BOOTFILE} not present.. .." >> "${PRE_PARAM_LOG}"
     return 1;
  fi

  if [ -f /etc/default/grub ]; then
     CHANGE_FILE=/etc/default/grub
  else
     CHANGE_FILE=${BOOTFILE}
  fi

  export BOOTFILE BOOTDIR CHANGE_FILE GRUB_EFI
  export CHANGE_FILE_INIT_BACKUP="${CHANGE_FILE}-initial.orabackup"

  return 0;
}

# Function for Workaround of Orabug 20734786
f_grub2_mkconfig ()
{
   grub2_options=""
   #f_checkgrub needs to have been called before this function
   if [ "$GRUB_VER" -ne 2 ]; then
      return 0;
   fi;

   if [ "$GRUB_EFI" -eq 1 ]; then
      echo "EFI system"  >> "${PRE_PARAM_LOG}"
      G_DIR=${GRUB_EFI_DIR}
   else
      G_DIR=${GRUB2_DIR}
   fi;

   export G_DIR
   echo "G_DIR=$G_DIR" >> "${PRE_PARAM_LOG}"

   echo "Getting all the available kernels on the system" >> "${PRE_PARAM_LOG}"
   grubby --info=ALL | tr -s "\n" ":" | sed 's/index/\nindex/g' >> "${PRE_PARAM_LOG}"

   current_default=$(grubby --default-kernel)
   echo "Default Kernel -> $current_default" >> "${PRE_PARAM_LOG}"
   echo "Running Kernel -> $(uname -r)" >> "${PRE_PARAM_LOG}"
   echo "Saving a copy of grubenv... in ${BACKUP_DIR}" >> "${PRE_PARAM_LOG}"

   mkdir -p "${BACKUP_DIR}"
   cp ${G_DIR}/grubenv "${BACKUP_DIR}"/grubenv."$(date +%d-%m-%y-%H-%M-%S)"

   if [ "$LDISTRO" -ge 9 ]; then
      grub2_options="--update-bls-cmdline"
   fi

   echo "Running grub2-mkconfig" >> "${PRE_PARAM_LOG}"
   grub2-mkconfig -o "${BOOTFILE}" "${grub2_options}" >> "${PRE_PARAM_LOG}" 2>&1
   retval=$?

   echo "Setting the default back to ${current_default}" >> "${PRE_PARAM_LOG}"
   grubby --set-default="${current_default}"
   let retval=$?+$retval

   echo "Default has been set to - $(grubby --default-kernel)"
   return $retval
}

#A backup of the original menu.lst is also  mainatained at $BACKUP_DIR
f_checkboot ()
{
  declare -i flag=0;

  KERNEL_PRE_PARAM_LOG="${TEST_LOG_LOC}/kernel_bootparams.org";

  f_checkgrub;
  if [ $? -ne 0 ]; then return 1; fi;

  # Critical section - Reading and changing boot parameters 
  f_lock 

  if [ ! -f "${CHANGE_FILE_INIT_BACKUP}" ]; then
     echo "Saving a copy of ${CHANGE_FILE} file in ${CHANGE_FILE_INIT_BACKUP}" >> "${PRE_PARAM_LOG}"
     cp ${CHANGE_FILE} ${CHANGE_FILE_INIT_BACKUP};
  fi;

  # If there is a previous file by name ${BOOTFILE}-${PREINFILE}.orabackup, remove that
  if [ -f "${CHANGE_FILE}"-"${PREINFILE}".orabackup ]; then
     echo "Removing previous backup by the same name - $(ls "${CHANGE_FILE}"-"${PREINFILE}".orabackup)" >> "${PRE_PARAM_LOG}"
    rm -f "${CHANGE_FILE}"-"${PREINFILE}".orabackup
  fi

  CHANGE_FILE_BACKUP="${CHANGE_FILE}"-"${PREINFILE}".orabackup
  mkdir --mode 0700 -p "${BACKUP_DIR}";
  /bin/cp "${BOOTFILE}" "${BACKUP_DIR}" 2>/dev/null
  if [ "$?" -ne "0" ]; then
    echo "Failed to copy ${BOOTFILE} to ${BACKUP_DIR}.. .." >> "${PRE_PARAM_LOG}"
    f_unlock;
    return 1;
  fi

  if [ ! -f "${BOOTFILE}"-"${PREINFILE}".orabackup ]; then
     /bin/cp ${BOOTFILE} "${BOOTFILE}"-"${PREINFILE}".orabackup
     if [ "$?" -ne "0" ]; then
        echo "Failed to copy ${BOOTFILE} to ${BOOTFILE}-${PREINFILE}.orabackup.." >> "${PRE_PARAM_LOG}"
        f_unlock;
        return 1;
     fi
  fi

  echo "Saving a copy of ${CHANGE_FILE} in ${BACKUP_DIR}..." >> "${PRE_PARAM_LOG}"
  /bin/cp "${CHANGE_FILE}" "${BACKUP_DIR}" 2>/dev/null
  if [ "$?" -ne "0" ]; then
    echo "Failed to copy ${CHANGE_FILE} to ${BACKUP_DIR}.. .." >> "${PRE_PARAM_LOG}"
    f_unlock;
    return 1;
  fi

  echo "Verifying kernel boot parameters as per Oracle recommendations..." >> "${PRE_PARAM_LOG}"

  # Take a backup of existing grubby information
  echo "INFO: Current Kernel configuration" >> "${PRE_PARAM_LOG}"
  grubby --info=ALL 2>&1 >> "${PRE_PARAM_LOG}"
  
  while read line
  do
    # skip comments
    echo "$line" | /bin/grep -e "^#" > /dev/null
    if [ "$?" == "0" ]; then
      continue;
    fi
		
    CATEGORY=$(echo "$line" | $CUT -d":" -f1 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
    if [ "x${CATEGORY}" == "xboot" ] ; then
      ARCH=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      PROCESSOR=$(echo "$line" | $CUT -d":" -f3 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      PARAM=$(echo "$line" | $CUT -d":" -f6 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      RECVALUE=$(echo "$line" | $CUT -d":" -f7 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      param_str="$PARAM=$RECVALUE"
	
      if [ "x${ARCH}" == "x*" -o "x${ARCH}" == "x${LARCH}" ] ; then
        if [ "x${PROCESSOR}" == "x*" -o "x${PROCESSOR}" == "x${LPROCESSOR}" ] ; then
	  #Bug 31318578 - Do not set numa off on HP Superdome
          echo "${param_str}" | grep "numa=off" >/dev/null 2>&1
          if [ "$?" -eq "0" ]; then
            ls /proc/sgi_uv >/dev/null 2>&1
            if [ $? -eq 0 ]; then
              echo "INFO: Found /proc/sgi_uv, numa=off will not be set" >> "${PRE_PARAM_LOG}"
              continue;
            fi
          fi
          echo "${param_str}" | grep "transparent_hugepage" >/dev/null 2>&1
          if [ "$?" -eq "0" ]; then
             thpvalue=$RECVALUE
             # Disabling THP for note1557478.1, bug17029612 
             if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
                echo "${thpvalue}" > /sys/kernel/mm/transparent_hugepage/enabled
                echo "Setting /sys/kernel/mm/transparent_hugepage/enabled to ${thpvalue}" >> "${PRE_PARAM_LOG}"
                echo "" >> "${PRE_PARAM_LOG}"
             fi
             if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
                echo "${thpvalue}" > /sys/kernel/mm/transparent_hugepage/defrag
                echo "Setting /sys/kernel/mm/transparent_hugepage/defrag to ${thpvalue}" >> "${PRE_PARAM_LOG}"
                echo "" >> "${PRE_PARAM_LOG}"
             fi
          fi
          echo "INFO: Executing grubby --update-kernel=ALL args=$param_str" >> "${PRE_PARAM_LOG}"
          grubby --update-kernel=ALL --args="${param_str}" 2>&1 >> "${PRE_PARAM_LOG}"
          result=$?
          if [ $result -ne 0 ]; then
             echo "ERROR: Unable to add bootparam $param_str. Please execute manually" >> "${PRE_PARAM_LOG}"
             flag=1
          fi
          # Change in the /etc/default/grub file so that it is effective when grub2-mkconfig is run by any user
          if [ "${GRUB_VER}" -eq 2 ]; then
             # Get the lines to be changed copied over so that we can use the same logic for adding the params
             grep "GRUB_CMDLINE_LINUX" "${CHANGE_FILE}" | cut -d "=" -f2- > "${KERNEL_PRE_PARAM_LOG}"
          fi # GRUB_VER
          while read kernel_bootparam
          do
            # set to recommended value if not already set
            echo "$kernel_bootparam" | /bin/grep "${PARAM}" > /dev/null
            if [ $? -ne 0 ]; then
              echo "$kernel_bootparam" | grep "\"" > /dev/null 2>&1
              if [ $? -ne 0 ]; then
                 new_kernel_bootparam="$kernel_bootparam $param_str";
              else
                 new_kernel_bootparam=$(echo "$kernel_bootparam" | tr -d "\"")
                 new_kernel_bootparam="\"$new_kernel_bootparam $param_str\""
              fi

              $SED -i  "s%$kernel_bootparam.*$%$new_kernel_bootparam%g" "${CHANGE_FILE}"
              echo "INFO: old boot params: $kernel_bootparam" >> "${PRE_PARAM_LOG}"
              echo "INFO: new boot params: $new_kernel_bootparam" >> "${PRE_PARAM_LOG}"
              echo >> "${PRE_PARAM_LOG}"
            else
              l_value=$(echo "$kernel_bootparam" | tr -s " " "\n" | /bin/grep "${PARAM}" | cut -d "=" -f2 | tr -d "\"" | tail -1)
              echo "$l_value" | grep -i "${RECVALUE}" > /dev/null 2>&1
              if [ "$?" -ne "0" ]; then
                 $SED -i "s%${PARAM}=${l_value}%${param_str}%g" "${CHANGE_FILE}"
                 echo "Changing value of $PARAM from $l_value to $RECVALUE in ${CHANGE_FILE}" >> "${PRE_PARAM_LOG}"
              else
                 echo "INFO: ${param_str} already present in ${CHANGE_FILE}" >> "${PRE_PARAM_LOG}"
                 #Bug 31618334 . It is better to run grub2-mkconfig even though params are already present
                 #Params need not be set again
                 echo >> "${PRE_PARAM_LOG}"
              fi;
            fi;
          done < "${KERNEL_PRE_PARAM_LOG}"
	fi # PROCESSOR
      fi # ARCH
    fi # CATEGORY
  done < "${PARAMS}" # READ PARAMS FILE
  cp "${CHANGE_FILE}" "${CHANGE_FILE_BACKUP}"
  if [ "${flag}" -eq 0 ]; then
     echo "INFO: grubby --info=ALL" >> "${PRE_PARAM_LOG}"
     grubby --info=ALL >> "${PRE_PARAM_LOG}"
     echo "INFO: Boot parameters will be effected on next reboot" >> "${PRE_PARAM_LOG}"
     echo "INFO: Altered file ${CHANGE_FILE}" >> "${PRE_PARAM_LOG}"
     echo "INFO: Copy of the changed file is in - ${CHANGE_FILE_BACKUP}" >> "${PRE_PARAM_LOG}"
     echo "INFO: Copy of the original file is in - ${BACKUP_DIR}" >> "${PRE_PARAM_LOG}"
     echo "RUN_${RUN_PREINSTALL_EXPR}=NO" > "${CONFIG_FILE}"
  else
     echo "Unable to update boot parameters. Please execute manually" >> "${PRE_PARAM_LOG}"
  fi
  /bin/rm "${KERNEL_PRE_PARAM_LOG}" 2> /dev/null

  f_unlock;
  return 0;
}

f_set_dynamic_fs_file_max ()
{
  total_ram=$(grep "MemTotal" /proc/meminfo | awk -F " " '{ print $2}')
  if [ -n "$total_ram" ]; then
    RECVALUE=$((total_ram / 10))
    if [ "$RECVALUE" -lt 6815744 ]; then
      RECVALUE=6815744
    elif [ "$RECVALUE" -gt 33554432 ]; then
      RECVALUE=33554432
    fi
  fi
}

f_set_dynamic_fs_aio_max_nr ()
{
  total_ram=$(grep "MemTotal" /proc/meminfo | awk -F " " '{ print $2}')
  if [ -n "$total_ram" ]; then
    RECVALUE=$((total_ram / 16))
    if [ "$RECVALUE" -lt 4194304 ]; then
      RECVALUE=4194304
    elif [ "$RECVALUE" -gt 16777216 ]; then
      RECVALUE=16777216
    fi
  fi
}

# List files in procps sysctl --system order, including the package destination.
f_sysctl_files ()
{
  local dir file
  (
    # procps also loads dot-prefixed .conf files; keep this option local.
    shopt -s dotglob
    if [ "${1:-}" = "include_package" ]; then
      printf '%s\t%s\n' "${SYSCTL_PACKAGE##*/}" "${SYSCTL_PACKAGE}"
    fi
    for dir in "${SYSCTL_DIRS[@]}"; do
      for file in "${dir}"/*.conf; do
        [ -e "${file}" ] || [ -L "${file}" ] || continue
        printf '%s\t%s\n' "${file##*/}" "${file}"
      done
    done
  ) | awk -F '\t' '!seen[$1]++' | LC_ALL=C sort -t $'\t' -k1,1 | cut -f2- || return 1
  if [ -e "${SYSCTL}" ] || [ -L "${SYSCTL}" ] || [ "${2:-}" = include_sysctl ]; then
    printf '%s\n' "${SYSCTL}"
  fi
}

# Normalize assignments without evaluating configuration as shell code.
f_sysctl_records ()
{
  local file input
  while IFS= read -r file; do
    input=${file}
    [ "${file}" != "${SYSCTL_PACKAGE}" ] || input=$2
    if [ "${file}" = "${SYSCTL}" ] || [ "${file}" -ef "${SYSCTL}" ]; then
      input=$3
    fi
    [ -n "${input}" ] || continue
    awk -v source="${file}" -v package="${PREINFILE}" '
      function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t\r]+$/, "", s); return s }
      /^[ \t]*([#;]|$)/ { next }
      {
        line=$0; pos=index(line, "=")
        if (pos) {
          key=trim(substr(line, 1, pos-1)); sub(/^-/, "", key)
          value=substr(line, pos+1)
          # Strip whitespace-delimited comments for 26ai comparisons, not on disk.
          if (package == "oracle-ai-database-preinstall-26ai") sub(/[ \t]+[;#].*$/, "", value)
          value=trim(value); gsub(/[ \t]+/, " ", value)
        } else {
          key=trim(line); if (key !~ /^-/) next
          value="<exclude>"
        }
        gsub(/\//, ".", key)
        print key "\t" (value == "" ? "<empty>" : value) "\t" source
      }
    ' "${input}" || return 1
  done < "$1"
}

f_sysctl_read ()
{
  local key value source glob_value= glob_source= excluded=0 i matches
  local definitions= last_value= conflict=0
  local -a parts pattern
  local -a explicit_values=() explicit_sources=() glob_values=() glob_sources=()
  IFS=. read -r -a parts <<< "$1"
  SYSCTL_VALUE= SYSCTL_SOURCE=
  SYSCTL_MATCHED_VALUES=() SYSCTL_MATCHED_SOURCES=() SYSCTL_MATCHED_COUNT=0
  while IFS=$'\t' read -r key value source; do
    if [[ "${key}" == -* ]]; then
      [[ "$1" != ${key#-} ]] || excluded=1
      continue
    elif [ "${key}" = "$1" ]; then
      SYSCTL_VALUE=${value}
      SYSCTL_SOURCE=${source}
      explicit_values+=("${value}")
      explicit_sources+=("${source}")
    elif [[ "$1" == ${key} ]]; then
      # A filesystem glob cannot cross a sysctl path component.
      IFS=. read -r -a pattern <<< "${key}"
      [ "${#parts[@]}" -eq "${#pattern[@]}" ] || continue
      matches=1
      for ((i=0; i<${#parts[@]}; i++)); do
        [[ "${parts[i]}" == ${pattern[i]} ]] || matches=0
      done
      [ "${matches}" -eq 1 ] || continue
      glob_value=${value}
      glob_source=${source}
      glob_values+=("${value}")
      glob_sources+=("${source}")
    else
      continue
    fi
    if [ -n "${definitions}" ] && [ "${last_value}" != "${value}" ]; then conflict=1; fi
    definitions+="  ${source}: ${key} = ${value}"$'\n'
    last_value=${value}
  done < "$2"
  # Explicit assignments override globs regardless of their file order.
  if [ -n "${SYSCTL_SOURCE}" ]; then
    SYSCTL_MATCHED_VALUES=("${explicit_values[@]}")
    SYSCTL_MATCHED_SOURCES=("${explicit_sources[@]}")
    # A higher customer glob is still a configured preference worth retaining,
    # even though procps gives explicit assignments precedence when loading it.
    if [ "${excluded}" -eq 0 ] && [ -n "${glob_source}" ]; then
      SYSCTL_MATCHED_VALUES+=("${glob_values[@]}")
      SYSCTL_MATCHED_SOURCES+=("${glob_sources[@]}")
    fi
    SYSCTL_MATCHED_COUNT=${#SYSCTL_MATCHED_VALUES[@]}
  elif [ "${excluded}" -eq 0 ]; then
    SYSCTL_VALUE=${glob_value}
    SYSCTL_SOURCE=${glob_source}
    if [ -n "${glob_source}" ]; then
      SYSCTL_MATCHED_VALUES=("${glob_values[@]}")
      SYSCTL_MATCHED_SOURCES=("${glob_sources[@]}")
      SYSCTL_MATCHED_COUNT=${#glob_values[@]}
    fi
  fi
  if [ "${3:-}" = "log" ] && [ "${conflict}" -eq 1 ]; then
    printf 'WARN: Conflicting definitions for %s:\n%sEffective configured value: %s from %s. Verify that this precedence is intended.\n' \
      "$1" "${definitions}" "${SYSCTL_VALUE:-unset}" "${SYSCTL_SOURCE:-none}" >> "${PRE_PARAM_LOG}"
  fi
  return 0
}

# Limits use maxima; vectors and identifiers have parameter-specific rules.
f_sysctl_merge ()
{
  awk -v key="$1" -v old="$2" -v wanted="$3" '
    # Reject other bases rather than interpret a kernel octal value as decimal.
    function number(s) { return s ~ /^(0|[1-9][0-9]*)$/ }
    function maximum(a, b) {
      if (length(a) != length(b)) return length(a) > length(b) ? a : b
      return ("x" a) > ("x" b) ? a : b
    }
    BEGIN {
      if (old == "") old=wanted
      n=split(old, a, " "); m=split(wanted, b, " ")
      if (n != m) exit 1
      for (i=1; i<=n; i++) {
        if (!number(a[i]) || !number(b[i])) exit 1
      }
      if (key == "kernel.sem") {
        if (n != 4) exit 1
        for (i=1; i<=4; i++) printf "%s%s", maximum(a[i], b[i]), (i == 4 ? "\n" : " ")
      } else if (key == "net.ipv4.ip_local_port_range") {
        if (n != 2 || a[1]+0 > a[2]+0 || a[2]+0 > 65535) exit 1
        low=a[1]+0 < b[1]+0 ? a[1]+0 : b[1]+0
        high=a[2]+0 > b[2]+0 ? a[2]+0 : b[2]+0
        if (low % 2 == high % 2) {
          if (high < 65535) high++; else low--
        }
        print low " " high
      } else if (key == "vm.hugetlb_shm_group" ||
                 key == "kernel.panic_on_oops" || key ~ /^net\.ipv4\.conf\.(all|default)\.rp_filter$/) {
        if (n != 1) exit 1
        print wanted
      } else if (key ~ /^fs\.(file-max|aio-max-nr)$/ ||
                 key ~ /^kernel\.(shmmax|shmall|shmmni|panic)$/ ||
                 key ~ /^net\.core\.(rmem|wmem)_(max|default)$/) {
        if (n != 1) exit 1
        print maximum(old, wanted)
      } else exit 1
    }
  '
}

# Read back the selected settings once; do not change live values or customer files.
# Reusing the merge policy keeps limits, vectors and exact modes consistent.
f_sysctl_verify_live ()
{
  local param assignment expected actual merged status=0 warnings=0 count=0
  while read -r param assignment expected; do
    [ "${assignment}" = = ] || continue
    count=$((count + 1))
    if ! actual=$(/sbin/sysctl -n "${param}" 2>> "${PRE_PARAM_LOG}"); then
      printf 'ERROR: %s: expected=%s; actual=<unreadable>; live read failed\n' "${param}" "${expected}" >> "${PRE_PARAM_LOG}"
      status=1
      continue
    fi
    if ! actual=$(printf '%s\n' "${actual}" | awk '
      { gsub(/[[:space:]]+/, " "); if (NF) { $1=$1; printf "%s%s", sep, $0; sep=" " } }
      END { print "" }
    '); then
      printf 'ERROR: %s: expected=%s; actual=<unreadable>; normalization failed\n' "${param}" "${expected}" >> "${PRE_PARAM_LOG}"
      status=1
      continue
    fi
    if [ -z "${actual}" ]; then
      printf 'ERROR: %s: expected=%s; actual=<empty>; live read returned no value\n' "${param}" "${expected}" >> "${PRE_PARAM_LOG}"
      status=1
    elif ! merged=$(f_sysctl_merge "${param}" "${actual}" "${expected}"); then
      printf 'ERROR: %s: expected=%s; actual=%s; invalid live value or unsupported policy\n' "${param}" "${expected}" "${actual}" >> "${PRE_PARAM_LOG}"
      status=1
    elif [ "${actual}" = "${expected}" ]; then
      printf 'PASS: %s: expected=%s; actual=%s; live value matches\n' "${param}" "${expected}" "${actual}" >> "${PRE_PARAM_LOG}"
    elif [ "${merged}" = "${actual}" ]; then
      printf 'WARN: %s: expected=%s; actual=%s; higher or wider live value satisfies selected setting; left unchanged\n' "${param}" "${expected}" "${actual}" >> "${PRE_PARAM_LOG}"
      warnings=$((warnings + 1))
    else
      printf 'ERROR: %s: expected=%s; actual=%s; live value does not satisfy selected setting\n' "${param}" "${expected}" "${actual}" >> "${PRE_PARAM_LOG}"
      status=1
    fi
  done <<< "$1"
  if [ "${count}" -eq 0 ]; then
    echo 'ERROR: No selected sysctl settings available for live verification' >> "${PRE_PARAM_LOG}"
    status=1
  fi
  if [ "${status}" -ne 0 ]; then
    echo 'ERROR: Live sysctl verification failed; manual review required' >> "${PRE_PARAM_LOG}"
  elif [ "${warnings}" -ne 0 ]; then
    echo 'WARN: Live sysctl verification completed with warnings' >> "${PRE_PARAM_LOG}"
  else
    echo 'Live sysctl verification passed' >> "${PRE_PARAM_LOG}"
  fi
  return "${status}"
}

# Remove only adjacent marker/assignment pairs also present in the old snapshot.
# The value must match the marker recommendation; retain differing customer values.
f_sysctl_migrate ()
{
  awk -v package="${PREINFILE}" '
    function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t\r]+$/, "", s); return s }
    function marker(s) {
      if (s !~ /^[ \t]*#/) return ""
      sub(/^[ \t]*#[ \t]*/, "", s)
      if (index(s, package " setting for ") != 1) return ""
      s=substr(s, length(package " setting for ")+1); sub(/[ \t].*$/, "", s); return s
    }
    function assignment(s, key, p) {
      sub(/[;#].*$/, "", s); p=index(s, "=")
      if (!p || trim(substr(s, 1, p-1)) != key) return ""
      s=trim(substr(s, p+1)); gsub(/[ \t]+/, " ", s); return s
    }
    FILENAME == ARGV[1] {
      if (previous != "") {
        value=assignment($0, previous)
        expected=previous_comment; sub(/^.*[ \t]is[ \t]+/, "", expected)
        gsub(/\047/, "", expected)
        sub(/[ \t]+(on|per)[ \t].*$/, "", expected)
        expected=trim(expected); gsub(/[ \t]+/, " ", expected)
        if (value != "" && ("x" value) == ("x" expected)) saved[previous_comment SUBSEP $0]=1
      }
      previous=marker($0); previous_comment=$0; next
    }
    {
      if (pending != "") {
        value=assignment($0, pending)
        if (value != "" && saved[comment SUBSEP $0]) { pending=""; next }
        print comment; pending=""
      }
      pending=marker($0)
      if (pending != "") comment=$0; else print
    }
    END { if (pending != "") print comment }
  ' "$1" "$2"
}

# Restore lines displaced by a previous 26ai run. Keep a managed assignment
# when an administrator changed it after installation.
f_sysctl_restore_26ai ()
{
  awk -v package="${PREINFILE}" -v logfile="${PRE_PARAM_LOG}" '
    function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t\r]+$/, "", s); return s }
    function assignment(s, p, key, value) {
      if (s ~ /^[ \t]*[#;]/) return ""
      sub(/[ \t]+[;#].*$/, "", s); p=index(s, "=")
      if (!p) return ""
      key=trim(substr(s, 1, p-1)); gsub(/\//, ".", key)
      value=trim(substr(s, p+1)); gsub(/[ \t]+/, " ", value)
      return key "=" value
    }
    {
      if (pending != "") {
        if (assignment($0) == expected) { pending=""; expected=""; next }
        print "WARN: Customer edited managed sysctl.conf assignment after " pending "; retaining it" >> logfile
        pending=""; expected=""
      }
      original="# " package " original: "
      marker="# " package " setting for "
      if ($0 == "# " package " created sysctl.conf") next
      if (index($0, original) == 1) { print substr($0, length(original)+1); next }
      if (index($0, marker) == 1) {
        entry=substr($0, length(marker)+1)
        p=index(entry, " is ")
        if (p) {
          pending=$0
          expected=substr(entry, 1, p-1) "=" substr(entry, p+4)
          next
        }
      }
      print
    }
    END { if (pending != "") print pending }
  ' "$1"
}

# Comment conflicting managed assignments, then place the selected Oracle
# values last in sysctl.conf. Unrelated customer lines are copied unchanged.
f_sysctl_stage_26ai ()
{
  awk -v package="${PREINFILE}" '
    function trim(s) { sub(/^[ \t]+/, "", s); sub(/[ \t\r]+$/, "", s); return s }
    function parse(s, p) {
      if (s ~ /^[ \t]*[#;]/) return ""
      sub(/[ \t]+[;#].*$/, "", s); p=index(s, "=")
      if (!p) return ""
      parsed_key=trim(substr(s, 1, p-1)); sub(/^-/, "", parsed_key)
      gsub(/\//, ".", parsed_key)
      parsed_value=trim(substr(s, p+1)); gsub(/[ \t]+/, " ", parsed_value)
      return parsed_key
    }
    FNR == NR {
      if (parse($0) != "") {
        selected[parsed_key]=parsed_value
        order[++count]=parsed_key
      }
      next
    }
    {
      key=parse($0)
      if (key in selected && parsed_value != selected[key])
        print "# " package " original: " $0
      else
        print
    }
    END {
      for (i=1; i<=count; i++) {
        key=order[i]
        print "# " package " setting for " key " is " selected[key]
        print key " = " selected[key]
      }
    }
  ' "$1" "$2"
}

# The last applicable entry in the parameter file supplies the recommendation.
f_sysctl_params ()
{
  awk -F: -v arch="${LARCH}" -v kernel="${LKERNEL}" -v distro="${LDISTRO}" '
    { for (i=1; i<=NF; i++) { sub(/^[ \t]+/, "", $i); sub(/[ \t]+$/, "", $i) } }
    $1 == "kernel" && ($2 == "*" || $2 == arch) &&
    ($3 == "*" || $3 == kernel) && ($4 == "*" || $4 == distro) {
      if (!($5 in entries)) order[++n]=$5
      entries[$5]=$1 ":" $2 ":" $3 ":" $4 ":" $5 ":" $6
    }
    END { for (i=1; i<=n; i++) print entries[order[i]] }
  ' "${PARAMS}"
}

#Add Oracle PRE recommended kernel parameters to the package-owned sysctl file.
f_checkkernel ()
{
  local is_26ai=0 status unlock_status=0
  [ "${PREINFILE}" != oracle-ai-database-preinstall-26ai ] || is_26ai=1
  SYSCTL_WARNING=0
  if ! f_lock; then
    if [ "${is_26ai}" -eq 0 ]; then return 1; fi
    echo "ERROR: Unable to lock sysctl configuration" >> "${PRE_PARAM_LOG}"
    SYSCTL_WARNING=1
    echo "WARNING: Preinstall sysctl configuration incomplete; review ${PRE_PARAM_LOG}" >&2
    return 0
  fi
  (
    set -o pipefail
    local work old_package= legacy= selected= status=0 live_status=0
    local legacy_existed=0 legacy_created=0 legacy_written=0 candidate i
    local CATEGORY ARCH KERNEL DISTRO PARAM RECVALUE records
    mkdir -p "${SYSCTL_DIR}" || exit 1
    if [ "${is_26ai}" -eq 1 ]; then
      mkdir -m 0700 -p "${BACKUP_DIR}" || exit 1
    else
      mkdir -p "${BACKUP_DIR}" || exit 1
    fi
    if [ -L "${SYSCTL_PACKAGE}" ]; then
      echo "ERROR: Review symlink ${SYSCTL_PACKAGE} before configuring sysctl" >> "${PRE_PARAM_LOG}"
      exit 1
    fi
    if [ "${is_26ai}" -eq 1 ] && [ -L "${SYSCTL}" ] && [ ! -f "${SYSCTL}" ]; then
      echo "ERROR: Review dangling or non-file symlink ${SYSCTL}" >> "${PRE_PARAM_LOG}"
      exit 1
    fi
    if [ "${is_26ai}" -eq 1 ] && [ -e "${SYSCTL_PACKAGE}" ] && [ -e "${SYSCTL}" ] &&
       [ "${SYSCTL}" -ef "${SYSCTL_PACKAGE}" ]; then
      echo "ERROR: ${SYSCTL} and ${SYSCTL_PACKAGE} refer to the same file" >> "${PRE_PARAM_LOG}"
      exit 1
    fi
    work=$(mktemp -d "${SYSCTL_DIR}/.${PREINFILE}.XXXXXX") || exit 1
    # Keep the cleanup path valid even if exit unwinds function-local variables.
    trap "$(printf 'rm -rf -- %q' "${work}")" EXIT
    if [ -f "${SYSCTL_PACKAGE}" ]; then
      old_package=${SYSCTL_PACKAGE}
      cp -p "${old_package}" "${BACKUP_DIR}/" || exit 1
    fi
    if [ -f "${SYSCTL}" ]; then
      legacy_existed=1
      legacy=${SYSCTL}
      if [ "${is_26ai}" -eq 1 ]; then
        cp -pL "${SYSCTL}" "${BACKUP_DIR}/sysctl.conf" || exit 1
        if grep -Fxq "# ${PREINFILE} created sysctl.conf" "${SYSCTL}"; then
          legacy_created=1
        fi
        if [ -n "${old_package}" ]; then
          f_sysctl_migrate "${old_package}" "${SYSCTL}" > "${work}/filtered" || exit 1
        else
          cat "${SYSCTL}" > "${work}/filtered" || exit 1
        fi
        f_sysctl_restore_26ai "${work}/filtered" > "${work}/legacy" || exit 1
        legacy=${work}/legacy
      elif [ -n "${old_package}" ] && [ ! -L "${SYSCTL}" ]; then
        cp -p "${SYSCTL}" "${work}/legacy" || exit 1
        f_sysctl_migrate "${old_package}" "${SYSCTL}" > "${work}/filtered" || exit 1
        cat "${work}/filtered" > "${work}/legacy" || exit 1
        if ! cmp -s "${SYSCTL}" "${work}/legacy"; then
          cp -p "${SYSCTL}" "${BACKUP_DIR}/sysctl.conf" || exit 1
          legacy=${work}/legacy
        fi
      fi
    elif [ "${is_26ai}" -eq 1 ]; then
      legacy_created=1
      : > "${work}/legacy" || exit 1
      legacy=${work}/legacy
    fi
    f_sysctl_files > "${work}/files" || exit 1
    : > "${work}/previous" || exit 1
    if [ "${is_26ai}" -eq 1 ]; then
      # Include the old package file in load order so cross-file conflicts are logged.
      f_sysctl_records "${work}/files" "${old_package}" "${legacy}" > "${work}/current" || exit 1
    else
      # Keep previous package values separately for older preinstall releases.
      f_sysctl_records "${work}/files" "" "${legacy}" > "${work}/current" || exit 1
      if [ -n "${old_package}" ]; then
        printf '%s\n' "${old_package}" |
          f_sysctl_records /dev/stdin "${old_package}" "${SYSCTL}" > "${work}/previous" || exit 1
      fi
    fi

    f_sysctl_params > "${work}/params" || exit 1
    [ -s "${work}/params" ] || exit 1
    printf '# %s kernel parameters\n' "${PREINFILE}" > "${work}/package" || exit 1
    while IFS=: read -r CATEGORY ARCH KERNEL DISTRO PARAM RECVALUE; do
      case "${PARAM}" in
        kernel.shmmax)
          case "${LARCH}" in
            i686) RECVALUE=4294967295 ;;
            x86_64) RECVALUE=4398046511104 ;;
          esac ;;
        kernel.shmall)
          case "${LARCH}" in
            i686) RECVALUE=2097152 ;;
            x86_64) RECVALUE=1073741824 ;;
          esac ;;
        vm.hugetlb_shm_group) RECVALUE=$(id -g oracle) || exit 1 ;;
        fs.file-max) f_set_dynamic_fs_file_max ;;
        fs.aio-max-nr) f_set_dynamic_fs_aio_max_nr ;;
      esac
      for records in "${work}/previous" "${work}/current"; do
        f_sysctl_read "${PARAM}" "${records}" log || exit 1
        if [ "${is_26ai}" -eq 1 ]; then
          for ((i=0; i<SYSCTL_MATCHED_COUNT; i++)); do
            candidate=${SYSCTL_MATCHED_VALUES[i]}
            if ! RECVALUE=$(f_sysctl_merge "${PARAM}" "${candidate}" "${RECVALUE}"); then
              echo "ERROR: Review ${PARAM} = ${candidate} in ${SYSCTL_MATCHED_SOURCES[i]}" >> "${PRE_PARAM_LOG}"
              exit 1
            fi
            echo "INFO: ${PARAM}: configured ${candidate} in ${SYSCTL_MATCHED_SOURCES[i]}; selected ${RECVALUE}" >> "${PRE_PARAM_LOG}"
          done
        else
          if ! RECVALUE=$(f_sysctl_merge "${PARAM}" "${SYSCTL_VALUE}" "${RECVALUE}"); then
            echo "ERROR: Review ${PARAM} = ${SYSCTL_VALUE} in ${SYSCTL_SOURCE}" >> "${PRE_PARAM_LOG}"
            exit 1
          fi
          if [ -n "${SYSCTL_SOURCE}" ]; then
            echo "INFO: ${PARAM}: configured ${SYSCTL_VALUE} in ${SYSCTL_SOURCE}; selected ${RECVALUE}" >> "${PRE_PARAM_LOG}"
          fi
        fi
      done
      printf '%s = %s\n' "${PARAM}" "${RECVALUE}" >> "${work}/package" || exit 1
    done < "${work}/params"

    # Confirm the staged file will remain effective after later customer files.
    if [ "${is_26ai}" -eq 1 ]; then
      f_sysctl_stage_26ai "${work}/package" "${legacy}" > "${work}/conf" || exit 1
      if [ "${legacy_created}" -eq 1 ]; then
        { printf '# %s created sysctl.conf\n' "${PREINFILE}"; cat "${work}/conf"; } > "${work}/created" || exit 1
        mv -f "${work}/created" "${work}/conf" || exit 1
      fi
      legacy=${work}/conf
      f_sysctl_files include_package include_sysctl > "${work}/files" || exit 1
    else
      f_sysctl_files include_package > "${work}/files" || exit 1
    fi
    f_sysctl_records "${work}/files" "${work}/package" "${legacy}" > "${work}/effective" || exit 1
    while read -r PARAM CATEGORY RECVALUE; do
      [ "${CATEGORY}" = "=" ] || continue
      f_sysctl_read "${PARAM}" "${work}/effective" || exit 1
      if [ "${SYSCTL_VALUE}" != "${RECVALUE}" ]; then
        echo "ERROR: ${SYSCTL_SOURCE} overrides ${PARAM} = ${RECVALUE} with ${SYSCTL_VALUE}; manual review required" >> "${PRE_PARAM_LOG}"
        status=1
      fi
    done < "${work}/package"
    [ "${status}" -eq 0 ] || exit 1
    if [ "${is_26ai}" -eq 1 ]; then
      # Snapshot before publishing/reloading: concurrent edits must not redefine
      # the selected values against which this installation is verified.
      selected=$(cat "${work}/package") || exit 1
    fi
    chmod 0644 "${work}/package" || exit 1
    if [ "${is_26ai}" -eq 1 ]; then
      if [ "${legacy_existed}" -eq 1 ]; then
        if ! cmp -s "${BACKUP_DIR}/sysctl.conf" "${SYSCTL}"; then
          echo "ERROR: ${SYSCTL} changed during verification; retry installation" >> "${PRE_PARAM_LOG}"
          exit 1
        fi
      elif [ -e "${SYSCTL}" ] || [ -L "${SYSCTL}" ]; then
        echo "ERROR: ${SYSCTL} appeared during verification; retry installation" >> "${PRE_PARAM_LOG}"
        exit 1
      fi
      if [ -n "${old_package}" ] && ! cmp -s "${BACKUP_DIR}/${SYSCTL_PACKAGE##*/}" "${SYSCTL_PACKAGE}"; then
        echo "ERROR: ${SYSCTL_PACKAGE} changed during verification; retry installation" >> "${PRE_PARAM_LOG}"
        exit 1
      fi
      if [ "${legacy_existed}" -eq 0 ] || ! cmp -s "${legacy}" "${SYSCTL}"; then
        if [ "${legacy_existed}" -eq 1 ]; then
          # Preserve the existing inode, permissions, symlink and file context.
          if ! cat "${legacy}" > "${SYSCTL}"; then
            cat "${BACKUP_DIR}/sysctl.conf" > "${SYSCTL}" || true
            exit 1
          fi
        elif ! install -m 0644 "${legacy}" "${SYSCTL}"; then
          rm -f "${SYSCTL}"
          exit 1
        fi
        legacy_written=1
      fi
    elif [ "${legacy}" = "${work}/legacy" ]; then
      # Preserve the existing inode, permissions and SELinux context.
      if ! cat "${legacy}" > "${SYSCTL}"; then
        cat "${BACKUP_DIR}/sysctl.conf" > "${SYSCTL}"
        exit 1
      fi
    fi
    if ! mv -f "${work}/package" "${SYSCTL_PACKAGE}"; then
      if [ "${is_26ai}" -eq 1 ] && [ "${legacy_written}" -eq 1 ]; then
        if [ "${legacy_existed}" -eq 1 ]; then
          cat "${BACKUP_DIR}/sysctl.conf" > "${SYSCTL}" || echo "ERROR: Failed to restore ${SYSCTL}" >> "${PRE_PARAM_LOG}"
        else
          rm -f "${SYSCTL}" || echo "ERROR: Failed to remove ${SYSCTL} after publish failure" >> "${PRE_PARAM_LOG}"
        fi
      else
        [ "${legacy}" != "${work}/legacy" ] || cat "${BACKUP_DIR}/sysctl.conf" > "${SYSCTL}"
      fi
      exit 1
    fi
    if [ "${is_26ai}" -eq 1 ]; then
      echo "Configured ${SYSCTL} and ${SYSCTL_PACKAGE}; backups in ${BACKUP_DIR}" >> "${PRE_PARAM_LOG}"
    else
      echo "Configured ${SYSCTL_PACKAGE}; backups in ${BACKUP_DIR}" >> "${PRE_PARAM_LOG}"
    fi
    /sbin/sysctl --system >> "${PRE_PARAM_LOG}" 2>&1 || status=$?
    if [ "${is_26ai}" -eq 1 ]; then
      if [ "${status}" -ne 0 ]; then
        echo "WARN: sysctl --system returned ${status}; checking managed live values" >> "${PRE_PARAM_LOG}"
      fi
      f_sysctl_verify_live "${selected}" || live_status=$?
      [ "${live_status}" -eq 0 ] || exit 1
      [ "${status}" -eq 0 ] || exit 2
      exit 0
    fi
    [ "${status}" -eq 0 ] || exit "${status}"
    exit "${live_status}"
  )
  status=$?
  f_unlock || unlock_status=$?
  if [ "${is_26ai}" -eq 1 ]; then
    [ "${unlock_status}" -eq 0 ] || status=1
    SYSCTL_WARNING=${status}
    if [ "${status}" -eq 1 ]; then
      echo "WARNING: Preinstall sysctl configuration incomplete; review ${PRE_PARAM_LOG}" >&2
    elif [ "${status}" -ne 0 ]; then
      echo "WARNING: sysctl --system reported errors; managed live values verified; review ${PRE_PARAM_LOG}" >&2
    fi
    return 0
  fi
  return "${status}"
}

#Add Oracle PRE recommended module options to /etc/modprobe.conf
#A backup of the original file /etc/modprobe.conf is maintained at /etc/modprobe.conf.orabackup
#A backup of the original /etc/modprobe.conf is also  mainatained at $BACKUP_DIR
f_checkmoduleinfo ()
{
  echo "Verifying module parameters as per Oracle recommendations..." >> "${PRE_PARAM_LOG}"
  MODCONF="/etc/modprobe.conf"
  MODCONFBACKUP="/etc/modprobe.conf.orabackup"
  f_lock;
  if [ ! -f "$MODCONFBACKUP" ]; then
    /bin/cp "${MODCONF}" "${MODCONFBACKUP}" ;
    if [ "$?" -ne "0" ]; then
      echo "Failed to copy ${MODCONF} to ${MODCONFBACKUP}.. .." >> "${PRE_PARAM_LOG}"
      f_unlock;
      return 1;
    fi
  fi

  /bin/cp "${MODCONF}" "${BACKUP_DIR}"
  if [ "$?" -ne "0" ]; then      
   echo "Failed to copy ${MODCONF} to ${BACKUP_DIR}.. .." >> "${PRE_PARAM_LOG}"
   f_unlock;
   return 1;
  fi

  FlowControlReset=0;
  for i in $(/sbin/ifconfig | /bin/awk ' /^[a-zA-Z0-9]+[ \t]+/ { print $1 } ')
  do
    /sbin/ethtool -i "$i"  > /dev/null 2>&1;
    if [ "$?" -eq "0" ]; then
      driver=$(/sbin/ethtool -i "$i" | /bin/grep -i "driver" | $CUT -d: -f2 | tr -d " ");
      if [ "x$driver" == "xe1000" ]; then
        if [ -z "$e1000Params" ]; then
          e1000Params="options e1000 FlowControl=1";
	  e1000List="$i"
	else
	  #For each e1000 card, append 1 to the end of "options e1000 FlowControl=1" 
	  e1000Params=$e1000Params,1
	  e1000List="$e1000List $i"
	fi
      fi
    fi
  done;
  if [ ! -z "$e1000Params" ] ; then
    /bin/grep "$e1000Params" "${MODCONF}" > /dev/null 2>&1;
    if [ $? -ne 0 ]; then
      if [ $(/bin/grep -c -e "^[ \t]*options[ \t]*e1000[ \t]*FlowControl.*$" ${MODCONF}) -eq 0 ]; then
        echo "$e1000Params" >> "${MODCONF}"
      else
	$SED -i 's/^[ \t]*'"options"'[ \t]*'"e1000"'[ \t]*'"FlowControl"'.*$/'"$e1000Params"'/' "${MODCONF}"
      fi
      FlowControlReset=1;
    else
      echo "Option $e1000Params already present in /etc/modprobe.conf" >>  "${PRE_PARAM_LOG}"
    fi
  fi

  if [ "${FlowControlReset}" -eq 1 ]; then
    echo "Setting module parameters as per Oracle recommendations..." >> "${PRE_PARAM_LOG}"
    echo "Altered file ${MODCONF}"  >> "${PRE_PARAM_LOG}"
    echo "Original file backed up at ${MODCONFBACKUP}" >> "${PRE_PARAM_LOG}"
    if [ -n "$e1000Params" ]; then
      for i in $(echo "$e1000List")
      do
        #For immediate effect of flowcontrol settings. FlowControl=1 translates to rx on, tx off
	/sbin/ethtool -A "$i" rx on 2> /dev/null
	/sbin/ethtool -A "$i" tx off 2> /dev/null
      done;
      /sbin/modprobe -v e1000 >>  "${PRE_PARAM_LOG}"
      if [ "$?" -eq "0" ]; then
        echo "e1000 settings modified to include FlowControl=1" >>  "${PRE_PARAM_LOG}"
	/usr/bin/tail -5 /var/log/messages >> "${PRE_PARAM_LOG}";
      else
        echo "e1000 settings modification failed to include FlowControl=1" >>  "${PRE_PARAM_LOG}"
        f_unlock;
	return 1;
      fi
    else
      echo "Warning: e1000  module settings not modified" >>  "${PRE_PARAM_LOG}"
      echo "module is not installed or not in use " >>  "${PRE_PARAM_LOG}"
    fi
  else
    echo "No settings to be modified" >> "${PRE_PARAM_LOG}"
  fi
  f_unlock;
  return 0;
}

#Add Oracle PRE recommended user limits parameters to /etc/security/limits.d/${PREINFILE}.conf
#A backup of the original file ${PREINFILE}.conf is mainatained at $BACKUP_DIR
f_checkuserinfo ()
{

  USER="oracle";
  total_ram=$(grep "MemTotal" /proc/meminfo | awk -F " " '{ print $2}')
  max_memlock=$(echo $(($total_ram*9/10)))

  f_lock;
  if [ -f "${LIMITSFILE}" ]; then
    /bin/cp -f "${LIMITSFILE}" "${BACKUP_DIR}"
    if [ "$?" -ne "0" ]; then
      echo "Failed to copy ${LIMITSFILE} to ${BACKUP_DIR}.. .." >> "${PRE_PARAM_LOG}"
      f_unlock;
      return 1;
    fi
    #Remove duplicate lines
    /bin/awk '! a[$0]++' "${LIMITSFILE}"  > "${LIMITSFILE}".tmp && /bin/mv "${LIMITSFILE}".tmp "${LIMITSFILE}"
    if [ "$?" -ne "0" ]; then
      echo "Failed to move ${LIMITSFILE}.tmp to ${LIMITSFILE}.. .." >> "${PRE_PARAM_LOG}"
      f_unlock;
      return 1;
    fi
  else
    touch "${LIMITSFILE}"
  fi

  echo "Verifying oracle user OS limits as per Oracle recommendations..." >> "${PRE_PARAM_LOG}"
  # if old ${OLD_PARAMS} present which was copied during %pre of rpm install , remove older 
  # comments. Otherwise it may conflict with new comments and settings.	
  if [ -f "${OLD_PARAMS}" ] ; then
    while read line
    do
      echo "$line" | /bin/grep -e "^#" > /dev/null
      if [ "$?" == "0" ]; then
        continue;
      fi
      CATEGORY=$(echo "$line "| $CUT -d":" -f1 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ "x${CATEGORY}" == "xusercomment" ] ; then
        TMP=$(echo "$line" | $CUT -d":" -f2 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
	if [ -z "${TMP}" ];then
	  continue
	fi
	ARCH=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        COMMENT=$(echo "$line" | $CUT -d":" -f3- | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
	if [ "x${ARCH}" == "x*" -o "x${ARCH}" == "x${LARCH}" ] ; then
	  if [ ! -z "${COMMENT}" ] ; then
            ${SED} -i /"^#[[:space:]]*$COMMENT"/d "${LIMITSFILE}"
	  fi
	fi
      else
        continue;
      fi

    done < "${OLD_PARAMS}"
  fi


  while read line
  do
    echo "$line" | /bin/grep -e "^#" > /dev/null
    if [ "$?" == "0" ]; then
      continue;
    fi
    CATEGORY=$(echo "$line" | $CUT -d":" -f1 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
    if [ "x${CATEGORY}" == "xusercomment" ] ; then
      TMP=$(echo "$line" | $CUT -d":" -f2 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ -z "${TMP}" ];then
        echo -e "\n" >> "${LIMITSFILE}"
	continue
      fi
      ARCH=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      COMMENT=$(echo "$line" | $CUT -d":" -f3- | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ "x${ARCH}" == "x*" -o "x${ARCH}" == "x${LARCH}" ] ; then
        if [ ! -z "${COMMENT}" ]; then
          ${SED} -i /"^#[[:space:]]*$COMMENT"/d "${LIMITSFILE}"
          echo "# $COMMENT" >> "${LIMITSFILE}"
	fi
      fi
    fi
    if [ "x${CATEGORY}" == "xuser" ] ; then
      ARCH=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      KERNEL=$(echo "$line" | $CUT -d":" -f3 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      DISTRO=$(echo "$line" | $CUT -d":" -f4 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      TYPE=$(echo "$line" | $CUT -d":" -f5 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      ITEM=$(echo "$line" | $CUT -d":" -f6 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      RECVALUE=$(echo "$line" | $CUT -d":" -f7 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')

      if [ "x$ITEM" == "xmemlock" ]; then
         if [ "x$LARCH" == "xi686" ]; then # For 32-bit arch, the limit should default to 3GB
            RECVALUE=3145728
         fi
         if [ "$RECVALUE" -lt "$max_memlock" ]; then
            RECVALUE="$max_memlock"
         fi
      fi

      if [ "x${ARCH}" == "x*" -o "x${ARCH}" == "x${LARCH}" ] ; then
        if [ "x${KERNEL}" == "x*" -o "x${KERNEL}" == "x${LKERNEL}" ] ; then
          if [ "x${DISTRO}" == "x*" -o "x${DISTRO}" == "x${LDISTRO}" ] ; then
	    if line=$(/bin/grep -w -e "^[[:space:]]*${USER}[[:space:]]*${TYPE}[[:space:]]*${ITEM}" "${LIMITSFILE}");
	    then
                 old=$(echo "$line" | awk -F ' ' '{print $4}')
                 if [ -z "$old" ]; then
                    echo -e "Not able to locate value of ${ITEM}" >>  "$PRE_PARAM_LOG"
                 else
                    echo "$RECVALUE" | grep "[[:alpha:]]\+" >/dev/null 2>&1
                    if [ $? -eq 0 ]; then
                       /bin/grep -w -v -e "^[[:space:]]*${USER}[[:space:]]*${TYPE}[[:space:]]*${ITEM}" "${LIMITSFILE}" > "${LIMITSFILE}".tmp &&  /bin/mv "${LIMITSFILE}".tmp "${LIMITSFILE}"
                       if [ "x$old" == "x$RECVALUE" ]; then
	                  echo "$line" >> "${LIMITSFILE}"
                          echo "$line" >>  "$PRE_PARAM_LOG"
                          echo "${ITEM} ${TYPE} limit is matching with preinstall config." >>  "$PRE_PARAM_LOG"
                       else
	                  echo "$USER   $TYPE   $ITEM    $RECVALUE" >> "${LIMITSFILE}"
	                  echo "$USER   $TYPE   $ITEM    $RECVALUE" >>  "$PRE_PARAM_LOG"
	                  echo -e "Changing  ${USER} ${TYPE} ${ITEM} to match preinstall config" >>  "$PRE_PARAM_LOG"
                       fi
                    else
		       old=$(echo "$line" | awk -F ' ' '{print $4}' | grep -m1 -o "[0-9]*" |grep -m1 -o "[0-9]*")
                       if [ -z "$old" ]; then
                          echo -e "Not able to locate a numeric value of ${ITEM}" >>  "$PRE_PARAM_LOG"
                       else
                       if [ "$RECVALUE" -ge "$old" ] ;then
                         /bin/grep -w -v -e "^[[:space:]]*${USER}[[:space:]]*${TYPE}[[:space:]]*${ITEM}" "${LIMITSFILE}" > "${LIMITSFILE}".tmp &&  /bin/mv "${LIMITSFILE}".tmp "${LIMITSFILE}"
          	         if [ "$?" -ne "0" ]; then
                            echo "Failed to move ${LIMITSFILE}.tmp to ${LIMITSFILE}.. .." >> "${PRE_PARAM_LOG}"
                            f_unlock;
                            return 1;
          	          fi
		          if [ "$RECVALUE" -eq "$old" ] ;then
	                     echo "$line" >> "${LIMITSFILE}"
                             echo "$line" >>  "$PRE_PARAM_LOG"
		             echo "${ITEM} ${TYPE} limit is matching with preinstall config." >>  "$PRE_PARAM_LOG"
                          else
	                     echo "$USER   $TYPE   $ITEM    $RECVALUE" >> "${LIMITSFILE}"
                             echo "$USER   $TYPE   $ITEM    $RECVALUE" >>  "$PRE_PARAM_LOG"
	                     echo -e "Changing  ${USER} ${TYPE} ${ITEM} to match preinstall config" >>  "$PRE_PARAM_LOG"
		           fi
                       else
	    	          echo "${ITEM} ${TYPE} limit is higher than preinstall config." >>  "$PRE_PARAM_LOG"
                          echo "$line" >>  "$PRE_PARAM_LOG"
	               fi
                    fi
                 fi # old not numeric check
              fi # $RECVALUE is alphabetical
 	    else
              echo "$USER   $TYPE   $ITEM    $RECVALUE" >> "${LIMITSFILE}"
	      echo -e "Adding ${USER} ${TYPE} ${ITEM} ${VALUE} ${RECVALUE}" >>  "$PRE_PARAM_LOG"
	    fi	
          fi
        fi
      fi
    fi	
  done < "${PARAMS}"

  #remove empty lines
  /bin/cat -s "${LIMITSFILE}"  > "${LIMITSFILE}".tmp &&  /bin/mv "${LIMITSFILE}".tmp "${LIMITSFILE}"
  if [ "$?" -ne "0" ]; then
    echo "Failed to move ${LIMITSFILE}.tmp to ${LIMITSFILE}.. .." >> "${PRE_PARAM_LOG}"
    f_unlock;
    return 1;
  fi
  echo "Setting oracle user OS limits as per Oracle recommendations..." >> "${PRE_PARAM_LOG}"
  echo "Altered file ${LIMITSFILE}" >> "${PRE_PARAM_LOG}"
  echo "Original file backed up at ${BACKUP_DIR}" >> "${PRE_PARAM_LOG}"
  f_unlock;
  return 0;
}

f_findnextid ()
{
   fname="$1"
   let nxtid=0
   let nxtid="$2"
   if [ "x$fname" == "x" ]; then
      echo "ERROR: File name missing"
      echo "Usage: f_findnext <filename> <numeric-id>"
      return 1;
   fi
   if [ "x$nxtid" == "x" ]; then
      echo "ERROR: Numeric ID missing"
      echo "Usage: f_findnext <filename> <numeric-id>"
      return 1;
   fi

   while [ "$nxtid" -lt "65535" ]; do
      awk -F ":" '{print $3}' "${fname}" | grep "^${nxtid}$" > /dev/null 2>&1
      if [ "$?" -ne "0" ]; then
         echo "$nxtid"
         return 0
      fi
      let nxtid=$nxtid+1
   done
   return 1;
}

#
#Add oracle user. If present ,do nothing but create the mandatory groups
f_createuser ()
{
  f_lock;

  # Obtain the list of groups and the required groupid from PARAMS file
  GROUPS="/tmp/groups.list"
  grep "^group:" "${PARAMS}" > "${GROUPS}"

  while read line; do
     num_fields=$(echo "$line" | awk -F":" '{print NF}')
     
     if [ "$num_fields" -ne "7" ]; then
        echo "Group name not as per format - group:arch:processor:kernel:distribution:gname:gid" >> "${PRE_PARAM_LOG}"
	echo "Not creating - $line" >> "${PRE_PARAM_LOG}"
        continue;
     fi

     gname=$(echo "$line" | cut -d ":" -f6)
     gidnum=$(echo "$line" | cut -d":" -f7)

     inval_gname=$(echo "$gname" | sed -e 's/[a-z]*[A-Z]*[0-9]*//g')
    
     if [ ! -z "${inval_gname}" ]; then
        echo "Group names should have only alphanumeric characters" >> "${PRE_PARAM_LOG}"
        echo "Not creating - $gname" >> "${PRE_PARAM_LOG}"
	continue;
     fi;

     inval_gidnum=$(echo "$gidnum" | sed -e 's/[0-9]//g')
    
     if [ ! -z "${inval_gidnum}" ]; then
        echo "Group id should have only numerals." >> "${PRE_PARAM_LOG}"
        echo "Not creating - $gname / $gidnum"  >> "${PRE_PARAM_LOG}"
        continue;
     fi

     #/bin/grep "^${gname}:" /etc/group > /dev/null 2>&1
     getent group "${gname}" > /dev/null 2>&1
     if [ $? -eq 0 ]; then 
        echo "Group ${gname} - Already exists. Not creating again."  >> "${PRE_PARAM_LOG}"
        continue;
     fi

     gidnum=$(f_findnextid /etc/group "$gidnum")
     if [ "$?" -ne "0" ]; then
        echo "Failed to get a group ID"
        return 1;
     fi
     echo "Adding group ${gname} with gid ${gidnum}" >> "${PRE_PARAM_LOG}"
     /usr/sbin/groupadd -g "${gidnum}" "${gname}"  >> "${PRE_PARAM_LOG}" 2>&1
  done < "${GROUPS}"
  rm -f "${GROUPS}"

  USERS="/tmp/users.list"
  grep "^username:" "${PARAMS}" > "${USERS}"

  while read line; do
     usname=$(echo "$line" | cut -d ":" -f6)
     uidnum=$(echo "$line" | cut -d":" -f7)
     primarygroup=$(echo "$line" | cut -d":" -f8 | cut -d"," -f1)
     secgroups=$(echo "$line" | cut -d":" -f8)

     num_fields=$(echo "$line" | awk -F":" '{print NF}')
    
     if [ "${num_fields}" -ne "8" ]; then
        echo "Username not in format - user:arch:processor:kernel:distribution:username:id:primarygroup,secgroups" >> "${PRE_PARAM_LOG}"
	echo "Not creating - $line" >> "${PRE_PARAM_LOG}"
        continue;
     fi

     inval_usname=$(echo "$usname" | sed -e 's/[a-z]*[A-Z]*[0-9]*//g')
     inval_uidnum=$(echo "$uidnum" | sed -e 's/[0-9]//g')

     if [ ! -z "${inval_usname}" ]; then
        echo "Username should have only alphanumeric characters" >>  "${PRE_PARAM_LOG}" 
        echo "Not creating - $usname" >> "${PRE_PARAM_LOG}"
        continue;
     fi

     if [ ! -z "${inval_uidnum}" ]; then
        echo "User id should have only numerals. Not creating this user" >>  "${PRE_PARAM_LOG}"
	continue;
     fi;

     #/bin/grep "^${usname}:" /etc/passwd > /dev/null 2>&1
     id "${usname}" > /dev/null 2>&1
     if [ $? -eq 0 ]; then 
        echo "User ${usname} - Already exists. Not creating or modifying."  >> "${PRE_PARAM_LOG}"
        continue;
     fi
     #usernum=$(cat /etc/passwd | sort -t: -g +2 -3 | grep -v nfsnobody | cut -f3 -d":" | tail -1)
     #if [ "${usernum}" -ge "${uidnum}" ]; then
     #  echo "User ID $uidnum has been already used or is lower.  So, taking the next available one."
     #  uidnum=$(expr $usernum + 1)
     #fi
     uidnum=$(f_findnextid /etc/passwd "$uidnum")
     if [ $? -ne 0 ]; then
        echo "Failed to get the next available User ID"
        return 1;
     fi
     # Add the user - password is disabled for oracle user.
     echo "Adding user ${usname} with user id ${uidnum}, initial login group ${primarygroup}, supplementary groups ${secgroups} and  home directory /home/${usname}" >> "${PRE_PARAM_LOG}"
    /usr/sbin/useradd -u "${uidnum}" -g "${primarygroup}" -G "${secgroups}" -d /home/"${usname}" "${usname}" >> "${PRE_PARAM_LOG}" 2>&1
    if [ "$?" -eq "0" ]; then
      echo "Changing ownership of /home/${usname} to ${usname}:${primarygroup}" >> "${PRE_PARAM_LOG}"
      /bin/chown "${usname}":"${primarygroup}" /home/"${usname}"  >> "${PRE_PARAM_LOG}" 2>&1
    else		
      echo "Failed to create user - ${usname}" >> "${PRE_PARAM_LOG}"
      f_unlock;
      return 1;
    fi
    echo "Please set password for user - ${usname}" >> "${PRE_PARAM_LOG}"
    userinfo=$(/usr/bin/id "${usname}")
    echo "${userinfo}" >> "${PRE_PARAM_LOG}"
  done < "${USERS}"

  rm -f "${USERS}"
  f_unlock;
  return 0;
}

#Modify PAM settings, If present do nothing.
f_checkpaminfo()
{
  echo "Verifying PAM setting as per Oracle recommendations..." >> "${PRE_PARAM_LOG}"
  PAMCONF="/etc/pam.d/login"
  PAMCONFBACKUP="/etc/pam.d/login.orabackup"
  f_lock;
  if [ ! -f "$PAMCONFBACKUP" ]; then
    /bin/cp "$PAMCONF" "$PAMCONFBACKUP" ;
    if [ "$?" -ne "0" ]; then
      f_unlock;
      return 1;
    fi
  fi
  /bin/cp "${PAMCONF}" "${BACKUP_DIR}"
  if [ "$?" -ne "0" ]; then      
    f_unlock;
    return 1;
  fi
  /bin/grep pam_limits.so "$PAMCONF" > /dev/null 2>&1;
  if [ "$?" -ne "0" ]; then
    echo "session    required     /lib/security/pam_limits.so" >> "${PAMCONF}"
    echo "Altered  PAM settings in /etc/pam.d/login" >> "${PRE_PARAM_LOG}"
    echo "Original file backed up at ${PAMCONFBACKUP}" >> "${PRE_PARAM_LOG}"
  else
    echo "PAM settings already present as recommended by oracle" >> "${PRE_PARAM_LOG}"
  fi
  f_unlock;
  return 0;
}

f_installsysconfignet ()
{
   # Add NOZEROCONF=yes to /etc/sysconfig/network
   # Orabug 36463832/39890507 - Do not set this for Oracle versions 19, 23, and 26.
   oraversion=$(echo "${PREINFILE}" | awk -F"-" '{print $NF}' | tr -d "a-z")
   case "${oraversion}" in
      19|23|26)
         echo "Setting parameters in ${SYSCONFIGNET} is not relevant for ${oraversion}" >> "${PRE_PARAM_LOG}"
         return 0;
      ;;
   esac

   echo "Trying to add NOZEROCONF parameter..." >> "${PRE_PARAM_LOG}"
   if [ ! -f "$SYSCONFIGNET" ]; then
      echo "$SYSCONFIGNET not found" >> "${PRE_PARAM_LOG}"
      return 1;
   fi

   f_lock;
   if [ ! -f "$SYSCONFIGNETBKP" ]; then
      echo "Taking a backup of existing file to $SYSCONFIGNETBKP" >> "${PRE_PARAM_LOG}"
      cp "$SYSCONFIGNET" "$SYSCONFIGNETBKP"
      cp "$SYSCONFIGNET" "${TEST_LOG_LOC}"
   fi

   grep "NOZEROCONF=yes" "$SYSCONFIGNET" > /dev/null 2>&1
   if [ "$?" -eq "0" ]; then
      grep "^#.*preinstall.*" "${SYSCONFIGNET}" > /dev/null 2>&1
      if [ "$?" -eq "0" ]; then
         echo "Parameter added by previous preinstall rpm" >> "${PRE_PARAM_LOG}"
         $SED -i "s/^#.*oracle.*preinstall.*:/# $PREINFILE :/g" "$SYSCONFIGNET"
      fi
      echo "Parameter already present" >> "${PRE_PARAM_LOG}"
      f_unlock;
      return 0;
   fi;
   echo "# ${PREINFILE} : Add NOZEROCONF=yes" >> "$SYSCONFIGNET"
   echo "NOZEROCONF=yes" >> "$SYSCONFIGNET"
   echo "Successfully added parameter NOZEROCONF to ${SYSCONFIGNET}" >> "${PRE_PARAM_LOG}"
   f_unlock;
   return 0;
}

f_unistallsysconfignet ()
{
  # Orabug 36463832/39890507 - Do not set this for Oracle versions 19, 23, and 26.
  oraversion=$(echo "${PREINFILE}" | awk -F"-" '{print $NF}' | tr -d "a-z")
  case "${oraversion}" in
     19|23|26)
        echo "Setting parameters in ${SYSCONFIGNET} is not relevant for ${oraversion}" >> "${PRE_PARAM_LOG}"
        return 0;
     ;;
  esac
  f_lock;
  echo "/^# ${PREINFILE}.*/ {
N
s/NOZEROCONF=yes//g
D
}" > /tmp/sysconfsed

  ${SED} -f /tmp/sysconfsed  "$SYSCONFIGNET" >  "$SYSCONFIGNET".tmp
  ${SED} '/^\s*$/d' "$SYSCONFIGNET".tmp > "$SYSCONFIGNET"
  rm -f  /tmp/sysconfsed "$SYSCONFIGNET".tmp
  echo "Successfully removed the added entries from $SYSCONFIGNET" >> "${PRE_PARAM_LOG}"
  f_unlock;
}

f_uninstallsysctl ()
{
  local managed_26ai=0 sysctlfile
  FINAL_PREINST=0

  # Check whether backup file exists for sysctl.conf
  # if  ${PARAMS} present remove older settings

  # Check if /etc/sysctl.d/99-<any-previous-timestamp>-oracle-*preinstall*.conf is present
  l_sysctlbackup=${SYSCTL_PACKAGE##*/}
  l_lastsaved=$(ls -t "${SYSCTL_DIR}"/*preinstall*.conf 2>/dev/null | awk -F"/" '{print $NF}' | head -1)

  f_lock || return 1
  if [ -e "${SYSCTL}" ] && [ -e "${SYSCTL_PACKAGE}" ] &&
     [ "${SYSCTL}" -ef "${SYSCTL_PACKAGE}" ]; then
    echo "ERROR: ${SYSCTL} and ${SYSCTL_PACKAGE} refer to the same file" >> "${PRE_PARAM_LOG}"
    f_unlock
    return 1
  fi
  [ -f "${SYSCTL}" ] || : > "${SYSCTL}" || { f_unlock; return 1; }
  # Development 26ai files use tagged assignments rather than full snapshots.
  if [ "${PREINFILE}" = oracle-ai-database-preinstall-26ai ] &&
     { grep -Fxq "# ${PREINFILE} kernel parameters" "${SYSCTL_PACKAGE}" 2>/dev/null ||
       grep -Fq "# ${PREINFILE} original: " "${SYSCTL}" 2>/dev/null ||
       grep -Fxq "# ${PREINFILE} created sysctl.conf" "${SYSCTL}" 2>/dev/null; }; then
    managed_26ai=1
    for sysctlfile in "${SYSCTL}" "${SYSCTL_DIR}"/99-oracle{,-ai}-database-preinstall-*-sysctl.conf; do
      [ -f "${sysctlfile}" ] || continue
      [ "${sysctlfile}" != "${SYSCTL_PACKAGE}" ] || continue
      grep -Fq "# ${PREINFILE} " "${sysctlfile}" || continue
      if ! f_sysctl_restore_26ai "${sysctlfile}" > "${sysctlfile}.tmp" ||
         ! cat "${sysctlfile}.tmp" > "${sysctlfile}"; then
        rm -f "${sysctlfile}.tmp"
        f_unlock
        return 1
      fi
      rm -f "${sysctlfile}.tmp"
    done
  fi
  echo "Saved sysctl file - ${l_sysctlbackup}" >> "${PRE_PARAM_LOG}"
  echo "Latest preinstall sysctl file in /etc/sysctl.d - ${l_lastsaved}" >> "${PRE_PARAM_LOG}"
  if [ "x$l_sysctlbackup" == "x$l_lastsaved" ]; then
    export FINAL_PREINST=1
  echo "This is the preinstall rpm that was installed recently..." >> "${PRE_PARAM_LOG}"
  if [ "${managed_26ai}" -eq 0 ] && [ -f "${PARAMS}" ]; then
    while read line
    do
      # skip comments
      echo "$line" | /bin/grep -e "^#" > /dev/null
      if [ "$?" == "0" ]; then
        continue;
      fi
      CATEGORY=$(echo "$line" | $CUT -d":" -f1 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      TMP=$(echo "$line" | $CUT -d":" -f2 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ -z "${TMP}" ];then
        continue
      fi
      if [ "x${CATEGORY}" == "xkernelcomment" ] ; then
        TMP=$(echo "$line" | $CUT -d":" -f3 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        if [ -z "${TMP}" ]; then
          COMMENT=$(echo "$line" | $CUT -d":" -f2- | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        else
          DISTRO=$(echo "$line" | $CUT -d":" -f2 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
          if [ "x${DISTRO}" == "x${LDISTRO}" ] ; then
            COMMENT=$(echo "$line" | $CUT -d":" -f3- | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
          else
            ARG=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
            case "${ARG}" in
                "fs.file-max" | "net.core.wmem_max" | "net.ipv4.ip_local_port_range" )
                  COMMENT=$(echo "$line" | $CUT -d":" -f2- | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
                ;;
                * )
                continue
                ;;
            esac
          fi
       fi
       if [ ! -z "${COMMENT}" ] ; then
         /bin/grep -v "#[[:space:]]*${COMMENT}" "${SYSCTL}" > "${SYSCTL}".tmp
         [ "$?" -le 1 ] && /bin/cat "${SYSCTL}".tmp > "${SYSCTL}"
         if [ "$?" -ne "0" ]; then
           echo "Failed to move ${SYSCTL}.tmp to  ${SYSCTL}.. .." >> "${PRE_PARAM_LOG}"
           f_unlock;
           return 1;
         fi
       fi
      else
       continue;
    fi
    done < "${PARAMS}"
    while read line
    do
      # skip comments
      echo "$line" | /bin/grep -e "^#" > /dev/null
      if [ "$?" == "0" ]; then
        continue;
      fi
      CATEGORY=$(echo "$line" | $CUT -d":" -f1 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      TMP=$(echo "$line" | $CUT -d":" -f2 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ -z "${TMP}" ];then
        continue
      fi
    if [ "x${CATEGORY}" == "xkernel" ] ; then
      ARCH=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      KERNEL=$(echo "$line" | $CUT -d":" -f3 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      DISTRO=$(echo "$line" | $CUT -d":" -f4 |  $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      PARAM=$(echo "$line" | $CUT -d":" -f5 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      RECVALUE=$(echo "$line" | $CUT -d":" -f6 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ "x${ARCH}" == "x*" -o "x${ARCH}" == "x${LARCH}" ] ; then
        if [ "x${KERNEL}" == "x*" -o "x${KERNEL}" == "x${LKERNEL}" ] ; then
          if [ "x${DISTRO}" == "x*" -o "x${DISTRO}" == "x${LDISTRO}" ] ; then
            #special cases for shmmax based on architecture
            if [ "$PARAM" == "kernel.shmmax" ]; then
              # Setting shmmax to 4GB on 32 bit machines
              if [ "x${LARCH}" = "xi686" ]; then
                RECVALUE=4294967295 ;
                # Setting shmmax  as per bz7256
              elif [ "x${LARCH}" = "xx86_64" ]; then
                RECVALUE=4398046511104 ;
              fi
            fi
            #special cases for shmall based on architecture
            if [ "$PARAM" == "kernel.shmall" ]; then
              if [ "x${LARCH}" = "xi686" ]; then
                RECVALUE=2097152;
              elif [ "x${LARCH}" = "xx86_64" ]; then
                RECVALUE=1073741824;
              fi
            fi
            #special cases for vm.hugetlb_shm_group
            if [ "$PARAM" == "vm.hugetlb_shm_group" ]; then
              usname="oracle"
              RECVALUE=$(id "$usname" -g)
            fi

            #special cases for fs.file-max based on total memory
            if [ "$PARAM" == "fs.file-max" ]; then
              f_set_dynamic_fs_file_max
            fi

            #special cases for fs.aio-max-nr based on total memory
            if [ "$PARAM" == "fs.aio-max-nr" ]; then
              f_set_dynamic_fs_aio_max_nr
            fi

            grep -w -v "^[[:space:]]*${PARAM}[[:space:]]*=[[:space:]]*$RECVALUE" \
            "${SYSCTL}" > "${SYSCTL}".tmp
            [ "$?" -le 1 ] && /bin/cat "${SYSCTL}".tmp > "${SYSCTL}"
            if [ "$?" -ne "0" ]; then
             echo "Failed to move ${SYSCTL}.tmp to  ${SYSCTL}.. .." >> "${PRE_PARAM_LOG}"
             f_unlock;
             return 1;
            fi
          fi
        fi
      fi
    fi
    done < "${PARAMS}"
  fi
  else
   export FINAL_PREINST=0;
   listofotherorafiles=$(ls "${SYSCTL_DIR}"/99-oracle{,-ai}-database-preinstall-*-sysctl.conf 2>/dev/null | grep -v "$PREINFILE")
   echo "Removing the special parameters, if any, from other preinstall files - $listofotherorafiles" >> "${PRE_PARAM_LOG}"
   # Remove the special parameters,if any, from the other preinstall files
   for sysctlfile in $(echo "${listofotherorafiles} ${SYSCTL}"); do
     grep "${PREINFILE}.*BEGIN" "$sysctlfile" > /dev/null 2>&1
     if [ $? -eq 0 ]; then
       if ! sed /${PREINFILE}.*BEGIN/,/${PREINFILE}.*END/d "$sysctlfile" > "${sysctlfile}.tmp" ||
          ! cat "${sysctlfile}.tmp" > "${sysctlfile}"; then
         rm -f "${sysctlfile}.tmp"
         f_unlock
         return 1
       fi
       rm -f "${sysctlfile}.tmp"
     fi
   done
  fi ### Check to see if this is the latest sysctl in /etc/sysctl.d
  #remove empty lines
  /bin/cat -s "${SYSCTL}" > "${SYSCTL}".tmp && /bin/cat "${SYSCTL}".tmp > "${SYSCTL}"
  if [ "$?" -ne "0" ]; then
   echo "Failed to move ${SYSCTL}.tmp to  ${SYSCTL}.. .." >> "${PRE_PARAM_LOG}"
   f_unlock
   return 1;
  fi

  rm -f "${SYSCTL}".tmp
  echo "Erasing ${SYSCTL_PACKAGE}" >> "${PRE_PARAM_LOG}"
  if ! rm -f "${SYSCTL_PACKAGE}"; then
    f_unlock
    return 1
  fi

  /sbin/sysctl --system >> "${PRE_PARAM_LOG}" 2>&1 ||
    echo "WARNING: Sysctl reload failed during removal; live values may remain unchanged until a later reload or reboot" >&2
  f_unlock
  return 0
}

f_uninstallgrub ()
{
  # Removing changes from grub.conf
  f_checkgrub;
  if [ $? -ne 0 ]; then 
     echo "Unable to get $BOOTFILE to perform uninstall actions" >> "${PRE_PARAM_LOG}";
     return 1;
  fi;

  #remove boot options. take a backup incase something goes wrong.
  f_lock;

  l_grubbackup=$(ls "${CHANGE_FILE}"-"${PREINFILE}".orabackup 2>/dev/null | awk -F"/" '{print $NF}' 2>/dev/null)
  l_lastsaved=$(ls -t "${CHANGE_FILE}"*preinstall*.orabackup 2>/dev/null | awk -F"/" '{print $NF}' | head -1 2>/dev/null)

  if [ "x$l_grubbackup" == "x" ]; then
     echo "Error - Unable to find the previous backup...${CHANGE_FILE}-${PREINFILE}.orabackup.   Exiting..." >> "${PRE_PARAM_LOG}"
     f_unlock;
     return 1;
  fi;

  # If this timestamp is not the last, nothing to be done
  # If this is the last saved backup,
  # Then, remove the grub entries from CHANGE_FILE
  # If there is any other oracle-*preinstall*.orabackup - call the most recent oracle-*preinstall*-verify -b to reinstate the boot values

  if [ "x$l_grubbackup" = "x$l_lastsaved" ]; then
    flag=1;
    # This is the latest change - so remove the entries from CHANGE_FILE
    echo "Remove entries from ${CHANGE_FILE}" >> "${PRE_PARAM_LOG}"
    while read line
    do
      # skip comments
      echo "$line" | /bin/grep -e "^#" > /dev/null
      if [ "$?" == "0" ]; then
        continue;
      fi

      CATEGORY=$(echo "$line" | $CUT -d":" -f1 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
      if [ "x${CATEGORY}" == "xboot" ] ; then
        ARCH=$(echo "$line" | $CUT -d":" -f2 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        PROCESSOR=$(echo "$line" | $CUT -d":" -f3 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        PARAM=$(echo "$line" | $CUT -d":" -f6 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        RECVALUE=$(echo "$line" | $CUT -d":" -f7 | $SED 's/^[ \t]*//' |  $SED 's/[ \t]*$//')
        param_str="$PARAM=$RECVALUE"
	
        if [ "x${ARCH}" == "x*" -o "x${ARCH}" == "x${LARCH}" ] ; then
          if [ "x${PROCESSOR}" == "x*" -o "x${PROCESSOR}" == "x${LPROCESSOR}" ] ; then
	    #Bug 31318578 - numa off not relevant on HP Superdome
            echo "${param_str}" | grep "numa=off" >/dev/null 2>&1
            if [ "$?" -eq "0" ]; then
               if test -f /proc/sgi_uv; then
                  echo "INFO: Found /proc/sgi_uv, numa=off is not relevant for this system" >> "${PRE_PARAM_LOG}"
                  continue;
               fi
            fi
            $SED -i  "s% $param_str%%g" "${CHANGE_FILE}"  > /dev/null 2>&1;
            echo "INFO: Executing grubby --update-kernel=ALL --remove-args=$param_str" >> "${PRE_PARAM_LOG}"
            grubby --update-kernel=ALL --remove-args="${param_str}" 2>&1 >> "${PRE_PARAM_LOG}"
            result=$?
            if [ $result -ne 0 ]; then
              echo "ERROR: Unable to remove bootparams $param_str. Please execute manually" >> "${PRE_PARAM_LOG}"
            fi
          fi
        fi
      fi
     done < "${PARAMS}"
     echo "INFO: Removed the boot parameters" >> "${PRE_PARAM_LOG}"
     grubby --info=ALL 2>&1 >> "${PRE_PARAM_LOG}"
  fi # End of check for the last file

  rm -f "${CHANGE_FILE}"-"${PREINFILE}".orabackup;  # Remove the current backup.
  if [ "${GRUB_VER}" -eq "2" ]; then
    rm -f "${BOOTFILE}"-"${PREINFILE}".orabackup
  fi

  f_unlock;
  return 0;
}
               
f_uninstallmodprobe ()
{
  f_lock;
  if [ -f /etc/modprobe.conf.orabackup ];  then
    /bin/mv /etc/modprobe.conf.orabackup /etc/modprobe.conf > /dev/null 2>&1
    /sbin/lsmod | $CUT -d" " -f1 | /bin/grep "e1000" > /dev/null 2>&1;
    if [ $? -eq 0 ]; then
      /sbin/modprobe -v e1000 2> /dev/null 1>&2
      if [ "$?" -ne "0" ]; then
        echo "module parameters reversion failed"
      fi
    fi
  fi
  f_unlock;
}

#This function is invoked during rpm uninstall. Roll back all configuration changes here
f_uninstall ()
{
  f_uninstallsysctl;
  if [ $? -ne 0 ]; then
     echo "Unable to remove sysctl settings" >> "${PRE_PARAM_LOG}"
     return 1;
  fi

  f_uninstallgrub;
  if [ $? -ne 0 ]; then
     echo "Unable to remove grub/grub2 settings" >> "${PRE_PARAM_LOG}"
     return 1;
  fi

  f_uninstallmodprobe;
  if [ $? -ne 0 ]; then
     echo "Unable to remove modprobe settings" >> "${PRE_PARAM_LOG}"
     return 1;
  fi

  # Remove the /etc/sysconfig/network entries
  f_unistallsysconfignet
   if [ $? -ne 0 ]; then
       echo "Failed to remove entries from $SYSCONFIGNET"
       return 1;
   fi

   # Now, after removing any of current entries - if any previous sysctl is there call its install portion again
   if [ "x$FINAL_PREINST" == "x1" ]; then
      l_otherpreinstall=$(ls -t "${SYSCTL_DIR}"/*preinstall*.conf 2> /dev/null | awk -F "/" '{print $NF}' 2>/dev/null | grep -v "${PREINFILE}" 2>/dev/null | head -1)
      echo "Other installed preinstallation rpm on this box - $l_otherpreinstall" >> "${PRE_PARAM_LOG}"
      if [ "x$l_otherpreinstall" != "x" ]; then
           l_script=$(echo "$l_otherpreinstall" | sed -e 's%^.*oracle%oracle%g' | sed -e 's%-sysctl.conf%%g')
           echo "Calling ${l_script}-verify" >> "${PRE_PARAM_LOG}"
           "${l_script}"-verify
           return $?;
      fi;
   fi
  return 0;
}

export PATH=$PATH:/usr/sbin:/sbin:/usr/bin
USER="$(/usr/bin/id -un -n)"
if [ "x${USER}" != "xroot" ]; then
  echo ""
  echo "Error: this script needs to be executed as root user"
  echo "Exiting.."
  echo ""
  exit 1;
fi

if [ "$#" -ge "1" ]; then
  while getopts ":ub" options; do
    case $options in
      u ) f_uninstall ; exit $? ;;
      b ) f_installsysconfignet; res=$?
          f_checkboot ; exit $? || $res ;;	
      h ) echo " Usage: ${PREINFILE}-verify [-u]" ; exit 1 ;;
      * ) echo " Usage: ${PREINFILE}-verify [-u]" ; exit 1 ;;
    esac
  done
fi

mkdir --mode 0700 -p "${TEST_LOG_LOC}";
/usr/bin/test -d "${TEST_LOG_LOC}" && /bin/rm -f "${TEST_LOG_LOC}"/* 2> /dev/null;

mkdir --mode 0700 -p "${BACKUP_DIR}";

f_createuser;
if [ $? -ne 0 ]; then
  echo "User creation failed " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
else
  echo "User creation passed " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
fi;

VERIFIER_STATUS=0
f_checkkernel ;
if [ $? -ne 0 ]; then
  VERIFIER_STATUS=1
  echo "Sysctl configuration failed; review ${PRE_PARAM_LOG}" >&2
  echo "Verification of certain kernel parameters failed. " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
elif [ "${SYSCTL_WARNING:-0}" -ne 0 ]; then
  echo "Verification of kernel parameters incomplete or reported reload errors; review ${PRE_PARAM_LOG}" >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
else
  echo "Verification & setting of kernel parameters passed " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
fi;

echo "Setting user limits using $LIMITSFILE" >> "${PRE_PARAM_LOG}"
echo "" >> "${PRE_PARAM_LOG}"
f_checkuserinfo ;
if [ "$?" -ne "0" ]; then
  echo "Verification of certain user limits failed. " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
else
  echo "Verification & setting of user limits passed " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
fi;

f_checkboot ;
if [ $? -ne 0 ]; then
  echo "Verification of boot parameters failed. " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
else
  echo "Verification & setting of boot parameters passed " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
fi;

f_installsysconfignet;
if [ $? -ne 0 ]; then
  echo "Setting $SYSCONFIGNET parameters failed. " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
else
  echo "Setting ${SYSCONFIGNET} parameters passed " >> "${PRE_PARAM_LOG}"
  echo "" >> "${PRE_PARAM_LOG}"
fi;

echo "Taking a backup of old config files under ${BACKUP_DIR} " >> "${PRE_PARAM_LOG}"

/bin/cp "${PRE_PARAM_LOG}" "${BACKUP_DIR}"
/bin/rm -f "${OLD_PARAMS}"

exit "${VERIFIER_STATUS}"
