#!/bin/bash
#
# Copyright 2022 Cohesity Inc.
#
# Author: Mahesh Kumar
#
# Apply a patch for a service and all its dependent patches on all the nodes.
# This is executed by the support user from the home folder.
#

# Standard places
readonly DATA_DIR="/home/cohesity/data"
readonly PATCHES_DIR="${DATA_DIR}/patches"
readonly HOTFIX_DIR="${DATA_DIR}/hotfix"
readonly HOTFIX_V2_DIR="${DATA_DIR}/hotfix_v2"
readonly HOTFIX_LIST=A6
readonly SOFTWARE_DIR="/home/cohesity/software"
readonly PATCH_BIN="${SOFTWARE_DIR}/crux/patch/bin"
readonly HOTFIX_TARFILE=A1
readonly HOTFIX_VERSION=A2
readonly VALID_ON=A3
readonly DODIN_FLAG="${DATA_DIR}/.dodin_mode"
readonly FIPS_FILE="/proc/sys/crypto/fips_enabled"
readonly UI_BUILD_INFO="${SOFTWARE_DIR}/crux/iris/ui_build_info.txt"
readonly CRUX_BIN="${SOFTWARE_DIR}/crux/bin"
readonly PATCH_HISTORY="${PATCHES_DIR}/patch_history.json"
readonly LATEST_PATCH="/home/cohesity/patch"
readonly PATCH_ARTIFACTS="${DATA_DIR}/patch_artifacts"
readonly AF_BUILD_INFO="af_build_info.txt"
readonly BASEOS_PATCHES_DIR="${DATA_DIR}/baseos_patches"

TEMP_DIRS_ARR=()

declare -A patch_name_to_file_name_map
patch_name_to_file_name_map["gandalf"]="gandalf_server"

EXEC_FILE_SUFFIX="_exec"

readonly CUSTOMER_MANAGED_BASEOS_MARKER_FILE="${DATA_DIR}/nexus/customer_managed_baseos"
dodin_mode="0"
if [ -f ${DODIN_FLAG} ]; then
  dodin_mode=$(cat ${DODIN_FLAG})
elif [ -f ${FIPS_FILE} ]; then
  dodin_mode=$(cat ${FIPS_FILE})
fi

ssh_cmd="sudo su -l cohesity -c"
if [ "${dodin_mode}" = "1" ]; then
  ssh_cmd="${PATCH_BIN}/pssh.sh localhost"
fi

# We do cluster-wide patch application by default.
# Local node patch application is supported only for cluster patch without
# security fixes(BaseOS patches).
LOCAL_PATCH_APPLICATION=""

PROGNAME=$(basename $0)
PROG_VERSION=1
lock_holder="NO"
trap unlock_script EXIT
trap "" SIGINT

function usage() {
  echo "Usage 1: ${PROGNAME} <service-patch-file>"
  echo "    <service-patch-file> is a single service patch like"
  echo "         apollo-6.5.1e_cpd-patch-2021Sep02-ddb022e8.tgz"
  echo
  echo "Usage 2: ${PROGNAME} <dependent-service-patch-files> ..."
  echo "    <dependent-service-patch-files> two or more service patch files"
  echo "    that are dependent, i.e. essential parts of the same patch/fix."
  echo "    All the dependent patch files should be listed as parameters."
  echo
  echo "Usage 3: ${PROGNAME} <cluster-patch-file>"
  echo "    <cluster-patch-file> is a cluster patch like"
  echo "         6.6.0d-p8-2022Feb19-60041d9c.tgz"
  echo
  echo "Usage 4: ${PROGNAME} <baseos-patch-file>"
  echo "    <baseos-patch-file is a patch file like"
  echo "         baseos-6.6.0d_u2_cpd-patch-2022Mar07-d20a8f33.tgz"
  echo
  exit 1
}

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

# Locking/unlocking ensuring running a single instance of the script:

# Note: this script shares the same lock with 'apply_hotfix.sh'
# (renamed as 'apply_patch.sh' when building the hotfix)
readonly LOCKDIR=${DATA_DIR}/.apply_patch.lock

function delete_temporary_files_and_directories() {
  local dirs_array=("$@")
  for dir in "${dirs_array[@]}"; do
    if [ ! -d ${dir} -a ! -f ${dir} ]; then
      continue
    else
      rm -rf ${dir}
    fi
  done
}

function unlock_script() {
  if [ "${lock_holder}" = "NO" ]; then
    # Losers do not have the right to delete the lock directory.
    return
  fi
  if [ -d ${LOCKDIR} ]; then
    rmdir ${LOCKDIR}
  fi
  delete_temporary_files_and_directories "${TEMP_DIRS_ARR[@]}"
}

function lock_script() {
  # 1st instance: hold lock until it is done before allowing another instance.
  # 2nd instance: emit error message and exit.
  mkdir ${LOCKDIR} 2> /dev/null
  if [ "$?" != "0" ]; then
    pids=$(pidof ${PROGNAME})
    if [ "$?" = "0" ]; then
      lock_holder="NO"
      echo "Another instance of ${PROGNAME} is already running [${pids}]."
      exit 1
    fi
  fi
  lock_holder="YES"
  return
}

# Obtain the right to run this script. Exit if another instance is running.
lock_script

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

function check_version() {
  local valid_list=$(echo $1)
  # Validate if the patch is from the correct patch branch.
  cluster_release=$(basename $(readlink ${SOFTWARE_DIR}) | \
    sed 's/_release-.*//')
  for valid in ${valid_list}
  do
    if [ "${valid}" = "${cluster_release}" ]; then
      return
    fi
  done
  echo "${patch} is not applicable for this release ${cluster_release}"
  exit 1
}

function check_dependency() {
  local dependencies=""
  local service=""
  local all_services=""
  local curr_deps=""
  for pf in ${patch_files}
  do
    patch=$(basename ${pf})
    if [ ! -f "${DATA_DIR}/${patch}" ]; then
      echo "Patch ${patch} is not found. Please copy it to ${DATA_DIR}."
      exit 1
    fi
    IFS='-' read -r -a patch_parts <<< $(basename ${patch})
    if [ "${patch_parts[2]}" != "patch" ]; then
      echo "${patch} is not a service patch file"
      exit 1
    fi
    service="${patch_parts[0]}"
    rel_list=$(tar -O -xf ${DATA_DIR}/${pf} \
      patches/apply_${service}_patch.sh | \
      fgrep 'VALID_ON=' | sed 's/VALID_ON=//;s/"//g')
    check_version "${rel_list}"
    curr_deps=$(tar -O -xf ${DATA_DIR}/${pf} \
      patches/apply_${service}_patch.sh | \
      fgrep 'DEPENDENCIES=' | sed 's/DEPENDENCIES=//;s/,/ /g')
    if [ "${curr_deps}" != "None" ]; then
      if [ -z "${dependencies}" ]; then
        # First dependency set found.
        dependencies="${curr_deps}"
      else
        if [ "${curr_deps}" != "${dependencies}" ]; then
          echo "Multiple dependent sets given: \"${curr_deps}\" and \
            \"${dependencies}\""
          echo "Apply them one dependent set at a time."
          exit 1
        fi
      fi
    else
      if [ ! -z "${dependencies}" ]; then
        echo "Dependent patches \"${dependencies}\" and independent patch"  \
          "\"${service}\" are given."
        echo "Apply them one after the other."
        exit 1
      fi
    fi
    if [ -z "${all_services}" ]; then
      all_services="${service}"
    else
      all_services="${all_services} ${service}"
    fi
  done
  # If dependent patches are given, check if all are given and nothing more.
  if [ ! -z "${dependencies}" ]; then
    # Dependent patches are found.
    local dependent_services=($(echo ${dependencies}))
    local given_services=($(echo ${all_services}))
    local default_ifs=${IFS}
    IFS=$'\n' deps=($(sort <<<"${dependent_services[*]}"))
    IFS=$'\n' svcs=($(sort <<<"${given_services[*]}"))
    if [[ "${deps[@]}" != "${svcs[@]}" ]]; then
      echo "Patches given: \"${svcs[@]}\". Expecting \"${deps[@]}\"."
      exit 1
    fi
    IFS=${default_ifs}
  fi
}

function get_new_patch_exec_md5sum() {
  if [ $# -ne 1 ]; then
    echo "Insufficient number of arguments provided. Required:1"
    exit 1
  fi

  local patch_scripts_path=$1
  local ps_tmp_dir="${DATA_DIR}/patch_scripts_tmp"
  rm -rf ${ps_tmp_dir}
  mkdir -p ${ps_tmp_dir}
  tar -xf ${patch_scripts_path} -C ${ps_tmp_dir} 2>&1 > /dev/null
  rc=$?
  if [ $rc -ne 0 ]; then
    echo "Failed to extract patch_scripts.tgz for computing md5sum."
    exit 1
  fi
  local patch_exec_new="${ps_tmp_dir}/crux/bin/patch_exec"
  if [ ! -f ${patch_exec_new} ]; then
    echo "patch_exec not found in patch_scripts.tgz for computing md5sum."
    exit 1
  fi
  local md5sum_new=($(md5sum ${patch_exec_new}))
  echo ${md5sum_new}
  return 0
}

function is_update_required() {
  if [ $# -ne 1 ]; then
    echo "Insufficient number of arguments provided. Required:1"
    exit 1
  fi
  local patch_scripts_path=$1
  local curr_md5sum=($(md5sum ${CRUX_BIN}/patch_exec))
  local new_md5sum=$(get_new_patch_exec_md5sum ${patch_scripts_path})

  if [ "${curr_md5sum}0" != "${new_md5sum}0" ]; then
    echo "Patch service needs to be restarted."
    return 0
  else
    echo "Patch service restart is not required."
    return 1
  fi
}

function restart_patch_service() {
  echo "Restarting patch service before applying patches."
  patch.sh stop > /dev/null 2>&1
  if [ "$?" != "0" ]; then
    echo "Failure Restarting patch service."
    exit 1
  fi
  patch.sh start > /dev/null 2>&1
  if [ "$?" != "0" ]; then
    echo "Failure Restarting patch service."
    exit 1
  fi
  echo "Success Restarting patch service."
}

function update_patch_scripts() {
  # Extract the patch scripts that may have fixes.
  ${ssh_cmd} "(cd ${DATA_DIR}; \
    sudo chmod -f 664 ${patch_files}; \
    sudo chown -f cohesity ${patch_files}; \
    tar xf ${DATA_DIR}/${cluster_patch} \
      patches/patch_scripts.tgz > /dev/null 2>&1)"
  if [ "$?" != "0" ]; then
    echo "Failed to extract patch_scripts.tgz from patch"
    exit 1
  fi

  # Now see whether restart will be required.
  local ps_path="${DATA_DIR}/patches/patch_scripts.tgz"
  is_update_required "${ps_path}"
  rc=$?
  if [ $rc -eq 1 ]; then
    echo "Not extracting patch_scripts as patch is already updated."
    return 0
  else
    echo "Patch service will be restarted. Please retry patch application"
  fi

  ${ssh_cmd} "(tar -C ${SOFTWARE_DIR} -xf ${ps_path} > /dev/null 2>&1 )"
  rc=$?
  if [ $rc -ne 0 ]; then
    echo "Failed to extract patch_scripts.tgz to software dir. rc: $rc"
    exit 1
  fi
  restart_patch_service
}

function copy_hotfix_v2_patches() {
  if [ -d ${HOTFIX_V2_DIR} ]; then
    if [ -f ${HOTFIX_DIR}/${HOTFIX_LIST} ] && [ -f ${HOTFIX_V2_DIR}/${HOTFIX_LIST} ]; then
      # append contents of hotfix_v2 to hotfix
      ${ssh_cmd} "cat ${HOTFIX_V2_DIR}/${HOTFIX_LIST} >> ${HOTFIX_DIR}/${HOTFIX_LIST}"
      if [ "$?" != "0" ]; then
	exit 1
      fi
      ${ssh_cmd} "mv ${HOTFIX_V2_DIR}/${HOTFIX_LIST} ${HOTFIX_DIR}/${HOTFIX_LIST}_v2_bak"
      ${ssh_cmd} "mv ${HOTFIX_V2_DIR}/metadata.json ${HOTFIX_DIR}/metadata.json_v2_bak"
      ${ssh_cmd} "mv ${HOTFIX_V2_DIR}/* ${HOTFIX_DIR}/"
    fi
  fi
}

function update_cluster_scripts() {
  # Extract the patch scripts and patch_exec that may have fixes.
  ${ssh_cmd} "(cd ${DATA_DIR}; \
    sudo chmod -f 664 ${cluster_patch}; \
    sudo chown -f cohesity ${cluster_patch}; \
    tar xf ${DATA_DIR}/${cluster_patch} > /dev/null 2>&1 ; \
    rm -f ${BASEOS_PATCHES_DIR}/${cluster_patch} > /dev/null 2>&1; \
    tar xf ${DATA_DIR}/${cluster_patch} > /dev/null 2>&1 ; \
    rm -f ${DATA_DIR}/${cluster_patch} > /dev/null 2>&1; \
    tar -C ${SOFTWARE_DIR} -xf patches/patch_scripts.tgz > /dev/null 2>&1 )"
  if [ "$?" != "0" ]; then
    echo "Failed to extract patch_scripts.tgz from patch"
    exit 1
  fi

  # Now see whether restart will be required.
  local ps_path="${DATA_DIR}/patches/patch_scripts.tgz"
  is_update_required "${ps_path}"
  rc=$?
  if [ $rc -eq 1 ]; then
    echo "Not extracting patch_scripts as patch is already updated."
    return 0
  else
    echo "Patch service will be restarted. Please retry patch application"
  fi

  ${ssh_cmd} "(tar -C ${SOFTWARE_DIR} -xf ${ps_path} > /dev/null 2>&1 )"
  rc=$?
  if [ $rc -ne 0 ]; then
    echo "Failed to extract patch_scripts.tgz to software dir. rc: $rc"
    exit 1
  fi
  echo ${HOTFIX_TARFILE} | grep -qE 'p[0-9]+s[0-9]+'
  rc=$?
  if [ $rc -ne 0 ]; then
    restart_patch_service
  fi
}

function check_full_patch_compatibility() {
  for file in "${HOTFIX_DIR}"/*.tgz; do
    if [ -f "${file}" ]; then
      check_patch_apply_compatibility "$file"
      rm -rf ${TEMP_DIR}
      rm -f ${logger_file}
    fi
  done
}

function check_patch_list_compatibility() {
  patch_list=$@
  for pf in ${patch_list}; do
    patch=$(basename ${pf})
    full_path="${DATA_DIR}/${patch}"
    if [ -f "${full_path}" ]; then
      check_patch_apply_compatibility "$full_path"
      rm -rf ${TEMP_DIR}
      rm -f ${logger_file}
    fi
  done
}

function check_patch_apply_compatibility() {
  tarfile=$1
  if [ ! -f ${tarfile} ]; then
    echo "Patch file ${tarfile} is missing."
    exit 12
  fi
  base_patch=$(echo `basename ${tarfile}`)
  # Skip patch compatibility check for baseos patch.
  if [[ "${base_patch}" = "baseos"* ]]; then
    return
  fi
  exec_tarfile=$(echo ${base_patch} | sed 's/-patch-[^-].*-/-/')
  svc=$(echo ${base_patch} | sed 's/-.*//')

  NEXUS_TEMP="/home/cohesity/data/nexus/tmp"
  TEMP_DIR="${NEXUS_TEMP}/${svc}"
  TEMP_PATCHES_DIR="${TEMP_DIR}/patches"
  PATCH_SCRIPTS="${TEMP_PATCHES_DIR}/patch_scripts.tgz"
  TEMP_PATCHES_CRUX_BIN="${TEMP_PATCHES_DIR}/crux/bin"
  COMPUTE_VERSION_SCRIPT="${TEMP_PATCHES_CRUX_BIN}/compute_version.py"
  PATCH_COMPATIBILITY_SCRIPT="${TEMP_PATCHES_CRUX_BIN}/patch_compatibility.py"
  PATCH_METADATA="${TEMP_PATCHES_CRUX_BIN}/patch_metadata.json"

  mkdir -p ${TEMP_DIR}
  TEMP_DIRS_ARR+=("${TEMP_DIR}")
  chmod 775 ${TEMP_DIR}

  # Create the file to capture the logs.
  logger_file=${PATCHES_DIR}/apply-${svc}.txt
  if [ -f ${logger_file} ]; then
    rm -f ${logger_file}
  fi

  # Create log file using cohesity user. Also set reqd permissions for
  # patches directory.
  ${ssh_cmd} "(cd ${DATA_DIR}; \
    mkdir --parents ${PATCHES_DIR}; sudo chmod 775 ${PATCHES_DIR}; \
    touch ${logger_file}; chmod 664 ${logger_file})"

  tar -C ${TEMP_DIR} -xf ${tarfile} > /dev/null 2>&1
  if [ "$?" != "0" ]; then
    echo "Untar error for ${tarfile}" >> ${err_file}
    exit ${PATCH_UNTAR_ERROR}
  fi

  tar -C ${TEMP_PATCHES_DIR} -xf ${TEMP_PATCHES_DIR}/${exec_tarfile} > /dev/null 2>&1
  if [ "$?" != "0" ]; then
    echo "Untar error for ${TEMP_PATCHES_DIR}/${exec_tarfile}"
    exit 14
  fi

  # Compute the target version for service/UI/agent component
  if [ "${svc}" = "ui" ]; then
    TEMP_UI_BUILD_INFO="${TEMP_PATCHES_DIR}/ui_build_info.txt"
    if [ ! -e "${TEMP_UI_BUILD_INFO}" ]; then
      echo "UI build info 'ui_build_info.txt' is missing in ${exec_tarfile}"
      exit 15
    fi
    target_version=$(cat ${TEMP_UI_BUILD_INFO} 2> /dev/null | \
      fgrep version | sed "s/ui version //")
  elif [[ "${svc}" = "_af_"* ]]; then
    TEMP_PATCH_ARTIFACTS="${TEMP_PATCHES_DIR}/patch_artifacts/${svc}/${AF_BUILD_INFO}"
    if [ ! -e "${TEMP_PATCH_ARTIFACTS}" ]; then
      echo "Agent build info ${AF_BUILD_INFO} is missing in ${exec_tarfile}"
      exit 16
    fi
    target_version=$(cat ${TEMP_PATCH_ARTIFACTS} 2> /dev/null | \
      fgrep version | sed "s/patch_exec version //")
  else
    EXEC_FILE="${patch_name_to_file_name_map[$svc]}"
    # Append suffix to components not listed in map
    if [[ -z "${patch_name_to_file_name_map[$svc]}" ]]; then
      EXEC_FILE="${svc}${EXEC_FILE_SUFFIX}"
    fi
    target_version=$(${TEMP_PATCHES_CRUX_BIN}/${EXEC_FILE} --version 2> /dev/null | \
      fgrep version | sed "s/${EXEC_FILE} version //")
    rm -rf ${TEMP_PATCHES_DIR}/crux
  fi
  target_release=$(echo ${target_version} | sed 's/.*-\(.*\)-.*/\1/')
  echo "Target release : ${target_release} " >> ${logger_file}

  # Compute the current version
  tar -C ${TEMP_PATCHES_DIR} -xf ${PATCH_SCRIPTS} > /dev/null 2>&1
  if [ "$?" != "0" ]; then
    echo "Error while untar patch_scripts"
    exit 17
  fi

  if [ ! -f "${COMPUTE_VERSION_SCRIPT}" ]; then
    echo "Compute version script is missing. No further validations." >> ${logger_file}
    return
  fi

  # If patch file not present, set epoch_ts = 0
  if [ ! -e "${LATEST_PATCH}" ]; then
    epoch_ts=0
  else
    patch_applied_at=$(jq -r '.PatchAppliedAt' "${LATEST_PATCH}")
    epoch_ts=$(date -d "$patch_applied_at" +%s)
  fi

  if [ ! -f "${PATCH_HISTORY}" ]; then
    echo "No previous patches present" >> ${logger_file}
    latest_component=""
  else
    latest_component=$(python3 ${COMPUTE_VERSION_SCRIPT} --latest_patch_epoch=${epoch_ts} --patch_history=${PATCH_HISTORY} --component=${svc} --log_file=${logger_file})
    EXIT_CODE="$?"
    # echo "Latest Component: ${latest_component}"
    if [ "${EXIT_CODE}" != "0" ]; then
      echo "Executing compute version failed."
      exit 18
    fi
    if [ -z "${latest_component}" ]; then
      # Retry with epoch_ts=0
      epoch_ts=0
      latest_component=$(python3 ${COMPUTE_VERSION_SCRIPT} --latest_patch_epoch=${epoch_ts} --patch_history=${PATCH_HISTORY} --component=${svc} --log_file=${logger_file})
      EXIT_CODE="$?"
      if [ "${EXIT_CODE}" != "0" ]; then
          echo "Executing compute version failed on retry."
          exit 19
      fi
    fi
  fi

  if [ -z "${latest_component}" ]; then
    echo "Pick cluster release version." >> ${logger_file}
    current_version=$(basename $(readlink ${SOFTWARE_DIR}) | \
      sed 's/_release-.*//')
  else
    ui="ui"
    # Look for latest_component's version
    if [ "${latest_component}" = "${ui}" ]; then
      current_version=$(cat ${UI_BUILD_INFO} 2> /dev/null | \
        fgrep version | sed "s/${latest_component} version //")
    elif [[ "${latest_component}" = "_af_"* ]]; then
      AGENT_BUILD_INFO="${PATCH_ARTIFACTS}/${latest_component}/${AF_BUILD_INFO}"
      # If AF_BUILD_INFO is not present, pick patch_exec version
      if [ ! -f "${AGENT_BUILD_INFO}" ]; then
        echo "Agent build info not present. Compute patch_exec version." >> ${logger_file}
        current_version=$(${CRUX_BIN}/patch_exec --version 2> /dev/null | \
          fgrep version | sed "s/patch_exec version //")
      else
        # For agents, patch_exec is present in version
        current_version=$(cat ${AGENT_BUILD_INFO} 2> /dev/null | \
          fgrep version | sed "s/patch_exec version //")
      fi
    else
      current_version=$(${CRUX_BIN}/${latest_component} --version 2> /dev/null | \
        fgrep version | sed "s/${latest_component} version //")
    fi
  fi

  # If cluster_version is empty at this point, pick the cluster sw version
  if [ -z "${current_version}" ]; then
    echo "Pick cluster release version." >> ${logger_file}
    current_version=$(basename $(readlink ${SOFTWARE_DIR}) | \
      sed 's/_release-.*//')
  fi

  current_release=$(echo ${current_version} | sed 's/.*-\(.*\)-.*/\1/')
  echo "Current release : ${current_release} " >> ${logger_file}

  if [ ! -f "${PATCH_COMPATIBILITY_SCRIPT}" ]; then
    echo "Patch compatibility script is missing."
    exit 20
  fi
  if [ ! -f "${PATCH_METADATA}" ]; then
    echo "Patch metadata is missing."
    exit 21
  fi

  # Check patch compatibility for apply patch
  echo "Check patch compatibility for ${current_release} and ${target_release}" >> ${logger_file}
  python3 ${PATCH_COMPATIBILITY_SCRIPT} --action=apply --patch_metadata=${PATCH_METADATA} --current_branch=${current_release} --target_branch=${target_release} --log_file=${logger_file}
  EXIT_CODE="$?"
  if [ "${EXIT_CODE}" = "0" ]; then
    echo "Patch is compatible for apply." >> ${logger_file}
  else
    echo "Patch cannot be applied."
    echo "Patch cannot be applied." >> ${logger_file}
    exit 22
  fi

  return
}

#---------------------------------------------------------------------------
# Start the work here.
#---------------------------------------------------------------------------

if [ $# -lt 1 ]; then
  if [ "${HOTFIX_TARFILE}" = "A1" ]; then
    usage
  else
    patch_files=${HOTFIX_TARFILE}
    cluster_patch=${HOTFIX_TARFILE}
  fi
else
  patch_files=$@
  cluster_patch=$1
  # Handle the case where nexus executes this script with the below arguments:
  # $: sh apply_patch.sh local
  # to locally apply the patch after upgrade.
  if [ $# -eq 1 -a "${1}0" = "local0" ]; then
    LOCAL_PATCH_APPLICATION="$1"
    patch_files=${HOTFIX_TARFILE}
    cluster_patch=${HOTFIX_TARFILE}
    # If patch is being applied locally, the current script will be run by
    # nexus (cohesity user). Also patch service would not have been started
    # on this node by nexus at this point in case of patching after upgrade.
    ssh_cmd="sh -c"
  fi
fi

patch_type="cluster"

# Check the type of the patches. It could be either a cluster patch or
# a service patch. It cannot be mixed. This can be identified by the
# first file in the parameters. Service patch could be further divided
# into many. Currently, exec and ui patches are supported. In the future
# agent, installer, and baseos will be supported.
echo
echo "Validating the parameters"
echo

patch_file=$(basename ${cluster_patch})
IFS='-' read -r -a name_parts <<< ${patch_file}

if [ "${name_parts[0]}" = "baseos" ]; then
  # Only BaseOS patches start with the name baseos.
  patch_type="baseos"
  if [ $# -gt 1 ]; then
    echo "$# parameters given. Expecting 1."
    exit 1
  fi
  if [ "${#name_parts[@]}" != "5" ]; then
    echo "Patch file name ${patch_file} is not valid."
    exit 1
  fi
  baseos_patch=${cluster_patch}
elif [ "${name_parts[2]}" = "patch" ]; then
  # For service patches, we have to check if dependent patches are given
  # properly.
  patch_type="service"
  if [ "${#name_parts[@]}" != "5" ]; then
    echo "Patch file name ${patch_file} is not valid."
    exit 1
  fi
  check_dependency
  update_patch_scripts
  source ${PATCH_BIN}/error_defines.sh
  if [[ ! -v SKIP_PATCH_COMPATIBILITY_CHECKS ]]; then
    # skip patch compat env is not set, meaning we
    # don't want to skip compat check.
    # NEVER use this, as in-compat patches
    # can lead to cluster instability.
    # Extremely rare cases, we would need this.
    check_patch_list_compatibility ${patch_files}
  fi
elif [ "${#name_parts[@]}" = "4" ]; then
  # It is a cluster patch.
  if [ $# -gt 1 ]; then
    echo "$# parameters given. Expecting 1."
    exit 1
  fi
  if [ ! -f "${DATA_DIR}/${patch_file}" ]; then
    echo "Patch ${cluster_patch} not found. Please copy it to ${DATA_DIR}"
    exit 1
  fi
  patch_type="cluster"
  patch=${cluster_patch}
  check_version "${VALID_ON}"
  # Create log file before running compatibility checks as it will take a lot
  # of time.
  APPLY_VERSION=$(echo ${patch_file}|sed 's/.tgz//')
  OUTFILE=${PATCHES_DIR}/${APPLY_VERSION}.out
  echo "Running Patch Compatibility checks. " \
    "This may take a few minutes..." > ${OUTFILE}
  # At this point, we have validated the parameters.
  update_cluster_scripts
  copy_hotfix_v2_patches
  source ${PATCH_BIN}/error_defines.sh
  if [[ ! -v SKIP_PATCH_COMPATIBILITY_CHECKS ]]; then
    # skip patch compat env is not set, meaning we
    # don't want to skip compat check.
    # NEVER use this, as in-compat patches
    # can lead to cluster instability.
    # Extremely rare cases, we would need this.
    check_full_patch_compatibility
  fi
else
  echo "Patch file name ${patch_file} is not valid."
  exit 1
fi

APPLY_VERSION=$(echo ${patch_file}|sed 's/.tgz//')
OUTFILE=${PATCHES_DIR}/${APPLY_VERSION}.out
SCRIPT=apply-cluster-patch
STATUS_DIR=${HOTFIX_DIR}
if [ "${patch_type}" = "cluster" ]; then
  ${ssh_cmd} "(cd ${DATA_DIR}; \
    mkdir --parents ${PATCHES_DIR}; sudo chmod 775 ${PATCHES_DIR}; \
    rm -f ${STATUS_DIR}/mypid ${STATUS_DIR}/mystatus ; \
    nohup ${PATCH_BIN}/${SCRIPT}\
      ${cluster_patch} ${LOCAL_PATCH_APPLICATION}> ${OUTFILE} 2>&1 & )"
  if [ "$?" != "0" ]; then
    echo "Applying cluster patch failed"
    exit 1
  fi
elif [ "${patch_type}" =  "service" ]; then
  SCRIPT=apply-service-patch
  STATUS_DIR=${PATCHES_DIR}
  ${ssh_cmd} "(cd ${DATA_DIR}; \
    mkdir --parents ${PATCHES_DIR}; sudo chmod 775 ${PATCHES_DIR}; \
    rm -f ${STATUS_DIR}/mypid ${STATUS_DIR}/mystatus ; \
    nohup ${PATCH_BIN}/${SCRIPT} \
      ${patch_files} > ${OUTFILE} 2>&1 & )"
  if [ "$?" != "0" ]; then
    echo "Applying service patch failed"
    exit 1
  fi
elif [ "${patch_type}" = "baseos" ]; then
  # Skip apply baseos patch in customer managed env
  if [ -f "$CUSTOMER_MANAGED_BASEOS_MARKER_FILE" ]; then
    echo "Skipping baseos patch in customer managed environment"
    exit 0
  fi
  SCRIPT=apply-baseos-patch
  STATUS_DIR=${PATCHES_DIR}
  log_file_name="$(echo $(basename ${baseos_patch}) | sed 's/.tgz//').out"
  echo "Status log can be found in" \
    "/home/cohesity/data/patches/${log_file_name}"

  ${ssh_cmd} "(cd ${DATA_DIR}; \
    rm -f ${OUTFILE}; \
    mkdir --parents ${PATCHES_DIR}; sudo chmod 775 ${PATCHES_DIR}; \
    rm -f ${PATCHES_DIR}/mypid; \
    nohup ${PATCH_BIN}/${SCRIPT} \
      ${baseos_patch} > ${OUTFILE} 2>&1 & )"
  if [ "$?" != "0" ]; then
    echo "Applying baseos patch failed"
    exit 1
  fi
fi

wait_cnt=0
while true
do
  sleep 2
  if [ -f ${STATUS_DIR}/mypid ]; then
    break
  fi
  let wait_cnt+=1
  if [ ${wait_cnt} -gt 10 ]; then
    if [ -f ${OUTFILE} ]; then
      cat ${OUTFILE}
    fi
    exit 9
  fi
done

cpid=$(cat ${STATUS_DIR}/mypid)
psstr=$(ps -h -p ${cpid})
if [ "$?" = "1" ]; then
  # process exited.
  cat ${OUTFILE}
  exit 10
fi

# Check if the pid is not recycled.
echo  ${psstr} | fgrep "${SCRIPT}" > /dev/null
if [ "$?" = "1" ]; then
  # process exited.
  cat ${OUTFILE}
  exit 11
fi

if [ "${LOCAL_PATCH_APPLICATION}0" = "local0" ]; then
  echo "Patch application log can be found at ${OUTFILE}"
  while [ -e /proc/${cpid} ]
  do
    echo "$(date) Waiting 30 seconds for the patch process to finish." \
      "cpid: $cpid"
    sleep 30
  done
  echo "$(date) Patching finished."
else
  tail --pid=${cpid} -f ${OUTFILE}
fi

exit_status=1
if [ -f ${STATUS_DIR}/mystatus ]; then
  exit_status=$(cat ${STATUS_DIR}/mystatus)
fi

exit ${exit_status}
