#!/usr/bin/env bash
# set -x
INSTALL_NOT_ATTEMPTED=3
seconds=$(date +%s)
usexml_file=
log_dir=/var/cpq
component_log_file=$log_dir/Component.log
disc_option=-d
disc_file_name=disc_file.xml
NSAC_file_name=NSAC_disc_file.xml
SAC_file_name=SAC_disc_file.xml
silent_option=-s
downgrade_option=-g
rewrite_option=-e
hpsum_flag=true
usexml_option=-u
force_option=-f
no_arg=false
SILENT_FLAG=false
valid_arg=false
internal_disc_option=-z
help_option=-h
sc_opt=0
sc_act=0
sc_user_opt=0

# Write information to stdout and the log file.
output() {
  if [[ $1 =~ "Error:" ]]; then
    printf "$1\nProgram exiting...\n" | tee -a $component_log_file
    exit 6
  else
    echo $1 | tee -a $component_log_file
  fi
}

#Adding Delimiter lines in Component log
addDelimiter(){
    if [ -f "$component_log_file" ]
    then
        echo "=================================================================" >> $component_log_file
    else
        echo "=================================================================" > $component_log_file
    fi

}

#Listing the Drives from the XML file
device_ids=()
selected_ids=()
list_device() {
  cnt=0
  indx=-1
  while IFS='' read -r line || [[ -n "$line" ]]
    do
      if [[ $line == *"device id"* ]]
      then
        cnt=`expr ${cnt} + 1`
        indx=`expr ${indx} + 1`
        devices[$indx]=`expr ${indx} + 1`")"
      fi
      if [[ $line == *"</device>"* ]]
      then
        cnt=`expr ${cnt} + 1`
      fi
      if [ `expr $cnt % 2` == 1 ]
      then
        if [[ $line == *"="* ]]
        then
          val=`echo $line | awk -F  "=\"" ' {print $2}'`
          #devices[$indx]=${devices[$indx]}" "${val%??}
          devices[$indx]=${devices[$indx]}" "`sed 's/[\/>]//g' <<< $val`
        fi
      fi
    done < $disc_file_name
  for i in "${devices[@]}"
  do
    echo ${i//\"} | awk '{print $1" "$4" Drive "$3" "$5" ("$10")"}'
    device_ids+=(`echo ${i//\"} | awk '{print $6}'`)
  done
}

# Selecting the drives based on the User input
read_option() {
  final_str=""
  if [[ $1 == "A" || $1 == "All" ]]
  then
    str=""
    for ((i=1;i<=${#device_ids[@]};i++))
    do
      final_str="$final_str$i "
    done
  elif [[ $1 == "N" || $1 == "None" ]]
  then
    break
    #for i in "${device_ids[@]}"
    #do
    #  idnum=`grep -n $i $disc_file_name | awk -F ":" '{print $1}'`
    #  actnum=`expr ${idnum} + 9`
    #  sed -i "${actnum}s/<action value=\".*\" \/>/<action value=\"skip\" \/>/" $disc_file_name
    #done
  elif [[ $1 =~ [^1-9,\-] || $1 =~ [,|\-]$  ||  $1 =~ ^[,|\-] || $1 =~ \-\- || $1 =~ ,, || $1 =~ \-, || $1 = ,\- ]]
  then
    echo "Invalid input, please try again"
    return 1
  else
    input=`echo $1 | sed -n 1'p' | tr ',' '\n'`
    while read word
    do
      if [[ $word == *"-"* ]]
      then
        str=""
        min=`echo "$word" | awk -F "-" '/-/ {print $1}'`
        max=`echo "$word" | awk -F "-" '/-/ {print $2}'`
        if [[ $min -gt ${#device_ids[@]} || $max -gt ${#device_ids[@]} || $min -ge $max ]]
        then
          echo "Invalid input, please try again"
          return 1
        fi
        for ((i=$min;i<=$max;i++))
        do
          str="$str$i "
        done
        final_str="$final_str$str "
      else
        if [[ $word -gt ${#device_ids[@]} ]]
        then
          echo "Invalid input, please try again"
          return 1
        else
          final_str="$final_str$word "
        fi
      fi
    done <<< "$(echo -e "$input")"
    list_num=( $final_str )
    for i in "${list_num[@]}"
    do
      selected_ids+=(${device_ids[`expr $i - 1`]})
    done
    all_device_ids=`echo ${selected_ids[*]}`
    for i in "${device_ids[@]}"
    do
      if [[ $all_device_ids != *"$i"* ]]
      then
        idnum=`grep -n $i $disc_file_name | awk -F ":" '{print $1}'`
        actnum=`expr ${idnum} + 7`
        sed -i "${actnum}s/<action value=\".*\" \/>/<action value=\"skip\" \/>/" $disc_file_name
      fi
    done
  fi
}
# Splitting the xml file based on the controller type
rm -f NSAC_disc_file.xml SAC_disc_file.xml
splitxml() {
  flag="both"
  while IFS='' read -r line
  do
    if [[ $line =~ [[:space:]]*\<device[[:space:]]id=\"AC:.*\> ]] 
    then
      ac_id=`grep -oP '(?<=AC:).*?(?=,)' <<< "$line"`
      if [[ $ac_id =~ ^[0-9]*$ ]]
      then
        flag="SAC"
      else
        flag="NSAC"
      fi
    elif [[ $line =~ [[:space:]]*\<device[[:space:]]id=\"NONSAPD:.*\> ]]
    then
      flag="SAC"
    elif [[ $line =~ [[:space:]]*\</devices\> ]]
    then
      flag="both"
    fi
    if [[ $flag == "both" ]]
    then
      printf "%s\n" "$line" >> $NSAC_file_name
      printf "%s\n" "$line" >> $SAC_file_name

    elif [[ $flag == "NSAC" ]]
    then
      printf "%s\n" "$line" >> $NSAC_file_name
    elif [[ $flag == "SAC" ]]
    then
      printf "%s\n" "$line" >> $SAC_file_name
    fi
  done < $usexml_file
}
#Crop the component logs and remove verbose logs
CropComponentLogFile() {
  str="Creating engineering log file at"
  if [[ -f $component_log_file ]]; then
    logfile=`grep $str $component_log_file -s | tail -1 |  awk '{print $6}'`
    rm -f $logfile
  fi
  linenumber=$(awk '/=================================================================/ { ln = FNR } END { print ln }' $component_log_file )
  if [[ ${linenumber} != "" ]]; then
    $(sed -i ${linenumber},\$d $component_log_file)
  fi
}

# This function checks to see if the file is readable.
isFileReadable() {
  if [[ ! -r $1 ]]; then
    output "Error: Installation not attempted, unmet dependence: Unable to read the $2 file."
  fi
}

# This function checks to see if the file is executable.
isFileExecutable() {
  if [[ ! -x $1 ]]; then
    output "Error: Installation not attempted, unmet dependence: Unable to execute the $2 file."
  fi
}

printUserPrompt() {
  # Print out the Smart Component prompt for the user.
  drive_counter=0
  interactiveWindow=false
  for arr_line in "${smart_component_prompt_arr[@]}"
  do
    if [[ $arr_line =~ "Select which devices to flash [#,#-#,(A)ll,(N)one]" ]]; then
      interactiveWindow=true
      # Break out of the loop when the initial user prompt is reached.
      break
    fi
    drive_listing="Drive[[:space:]]+[[:digit:]]+[[:alpha:]]:[[:digit:]]+:[[:digit:]]+"
    if [[ $arr_line =~ $drive_listing ]]; then
      # Count the number of drives that are displayed by the Smart Component.
      drive_counter=$(($drive_counter + 1))
    fi
    echo "$arr_line"
  done
  # Prompt the user for input.
  inventory_flag=false
  discovery_flag=false
  # Check to see if the user has requested and inventory.
  if [[ ! -z $@ ]]; then
    for arg in $@
    do
      if [[ $arg == "--inventory" ]]; then
        inventory_flag=true
      fi
      if [[ $arg == "--discovery" || $arg == "-d" ]]; then
        discovery_flag=true
      fi
    done
  fi
  # Don't display the user prompt if the user has requested an inventory list.
  if [[ $inventory_flag == "false" && $discovery_flag == "false" && $interactiveWindow == "true" ]]; then
    read -p "Select which devices to flash [#,(A)ll,(N)one]>" user_response
  else
    exit $retval
  fi
}
upperToLower() {
  lowercase=$(echo $1 | awk 'BEGIN { getline; print $1=tolower($1) }')
}

didPackageInstall() {
   upperToLower "$1"
   if echo "$results" | grep -w -q 'error\|fail'; then
     output "Error: The $package failed to install!"
     output "Exit Status: $INSTALL_NOT_ATTEMPTED"
     exit $INSTALL_NOT_ATTEMPTED
   fi
}


#Printing Actual Output from shasta console
consoleOutput(){
        tempOutput=$1
        while read -r line; do
                echo $line
        done <<< "$tempOutput"
}

#Manipulating user console output for shasta output
consoleOutputManipulation(){
        smart_component_prompt_arr=()
        output=$1
        delimiter_flag=true
        # storing each line in array
        while read -r line; do
                #echo $line
                smart_component_prompt_arr+=("$line")
        done <<< "$output"
        #ignoring after Exit status
        for line_element in "${smart_component_prompt_arr[@]}"
        do
		if [[ $line_element =~ "============ Summary ============" || $line_element =~ "Smart Component Finished" ]]; then
			continue
		fi
		if [[ $line_element =~ "Smart Component opted to not flash" ]]; then
			sc_opt=(`echo $line_element | awk '{print $7}'`)
		fi
		if [[ $line_element =~ "User opted to not flash" ]]; then
			sc_user=(`echo $line_element | awk '{print $6}'`)
		fi
		if [[ $line_element =~ "new FW image has been activated" ]]; then
			sc_act=(`echo $line_element | awk '{print $1}'`)
		fi
		if [[ $line_element =~ "new FW images have been activated" ]]; then
			sc_act=(`echo $line_element | awk '{print $1}'`)
		fi
		if [[ $line_element =~ "Exit Status:" ]]; then
			delimiter_flag=false
		fi
		if [[ "true" == $delimiter_flag ]]; then
			echo "$line_element"
		fi
	done
	export sc_opt_count=$sc_opt
	export sc_user_opt_count=$sc_user
	export sc_act_count=$sc_act
}

checkValidArguments() {

if [ -z "$1" ]
  then
    #echo "No argument supplied"
    no_arg=true
else
  #echo "Arguments passed"
  no_arg=false
fi

if [[ $no_arg == "false" ]]; then
   for arg in "$@"
   do
   if [[ $arg == "--silent" || $arg == "--usexml" || $arg == "--force" || $arg == "--rewrite" || $arg == "--discovery" || $arg == "--version" || $arg == "--interface" || $arg == "--inventory" || $arg == "--unpack" || $arg == "--help" || "--downgrade" == $arg || "--log-dir" == $arg || "--verbose-log" == $arg || "--force-ignore-timeouts" == $arg || "--force-ignore-bad-dev-status" == $arg || "-s" == $arg || "-u" == $arg || "-d" == $arg || "-f" == $arg || "-j" == $arg || "-k" == $arg || "-b" == $arg ||"-h" == $arg || "-e" == $arg || "-g" == $arg || "-?" == $arg ]]; then 
        valid_arg=true
        if [[ $arg == "-u" ]]; then
          break
        fi
        if [[ $arg == "--help" || "-?" == $arg || "-h" == $arg ]]; then
          smart_component_prompt_str="$(${PWD}/setup2 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} )"
          retval=$?
          # Break up the Smart Component prompt string on newlines and add it into an array.
          smart_component_prompt_arr=()
          while read -r line; do
            smart_component_prompt_arr+=("$line")
          done <<< "$smart_component_prompt_str"
          for arr_line in "${smart_component_prompt_arr[@]}"
          do
            echo "$arr_line"
          done
          if [[ 6 == $retval || 3 == $retval ]]; then
            echo "$component_output"
            exit $retval
          fi
        fi
        if [[ $arg == "-d" ]]; then
          break
        fi
     else
        #echo "Invalid Argument"
        valid_arg=false
        if [[ $arg == "-z" ]]; then
          smart_component_prompt_str="$(${PWD}/setup2 $help_option)"
        else
          smart_component_prompt_str="$(${PWD}/setup2 $arg)"
        fi
        retval=$?
        # Break up the Smart Component prompt string on newlines and add it into an array.
        smart_component_prompt_arr=()
        while read -r line; do
          smart_component_prompt_arr+=("$line")
        done <<< "$smart_component_prompt_str"
        for arr_line in "${smart_component_prompt_arr[@]}"
        do
          echo "$arr_line"
        done
        if [[ 6 == $retval ||  3 == $retval ]]; then
          echo "$component_output"
          exit $retval
        fi
     fi
   done
fi
}


getOSPlatform() {

# Determine what type of OS platform the script is running on and Storcli packages installation.
if [[ -f "/etc/redhat-release" || -f "/etc/SuSE-release" ]]; then
  RPMNAME=storcli-*.noarch.rpm
  chmod +x ${RPMNAME}
  rpm -qa | grep storcli &> /dev/null
  ret=$?
  if [[ $ret -ne 0 ]]; then
    rpm_install=$(rpm -ivh --replacepkgs --replacefiles "$RPMNAME" &> /dev/null)
    didPackageInstall $rpm_install
  fi
elif [ -f "/etc/debian_version" ]; then
  output "Info: You are running on an Debian based distribution!"
  DEBNAME=storcli_*.deb
  chmod +x ${DEBNAME}
  sudo dpkg -i --force-architecture ${DEBNAME}
else
  output "Info: You are running on a VMWare distribution!"
  #esxcli software vib list
  vibname=`find $PWD -type f -iname "vmware-esx-storcli*.vib"`
  esxcli software vib install -v="$vibname" --no-sig-check
fi
}

locateStorcli() {
#echo "locateStorcli"
# Locate where the storcli utility is installed.
# Once the installation directory is found, split the string containing the filenames into an array.
storcli_array=$(find / -type f \( -name "storcli64" -o -name "storclio64" -o -name "storcli" \) 2> /dev/null)
# The following for loop iterates over each file, the first executable file that is found will be used as the storcli executable file.
for file_name in $storcli_array
do
  if [ -x "$file_name" ]; then
    storcli=$file_name
  fi
done

# Verify that the variable contains an executable file.
if [ ! -x "$storcli" ]; then
  output "Error: Cannot find the storcli utility, please install either the storcli or storcli64 utility."
  output "Script Exiting."
  output "Exit Status: $INSTALL_NOT_ATTEMPTED"
  exit $INSTALL_NOT_ATTEMPTED
fi
}
main() {
    getOSPlatform
    locateStorcli
}
flash_warning=true

# Check to see if any of the command line arguments will result in a drive being flashed.
for arg in "$@"
do
  if [[ $arg =~ "--" && $arg =~ "silent" ||"-s" == $arg || $arg =~ "usexml" || "-u" == $arg || $arg =~ "discovery" || "-d" == $arg || $arg =~ "version" || $arg =~ "interface" || $arg =~ "inventory" || $arg =~ "unpack" || $arg =~ "help" || "-?" == $arg || "-h" == $arg ]]; then
    flash_warning=false
  fi
done

# first checking Invalid Arguments
checkValidArguments $@
main
#storcli=$PWD/storcli64
# This function checks to see if the file is executable.
#isFileExecutable $storcli "Storcli64"

# Check to see if there are drives connect to any supported storcli controller.
found_storcli_supported_drives_flag=false
number_of_controllers_present=$($storcli show ctrlcount | grep 'Controller Count =' | sed 's/.*=//' | sed 's/ //g')
if [[ 0 < $number_of_controllers_present ]]; then
  # This loop iterates over each supported controller until it finds a controller with drives attached.
  controller_id=0
  while [ "$controller_id" -le $(($number_of_controllers_present-1)) ]
  do
    cmd_status=$("$storcli" /c"$controller_id"/eall show | grep [0-9] | grep -v '=' | awk '{print $1}')
    if [[ $cmd_status =~ [0-9]+ ]]; then
      # If a drive is attached to a port, the cmd_status variable will contain the port's EID value.
      found_storcli_supported_drives_flag=true
      break
    fi
    controller_id=$(($controller_id + 1))
  done
fi

# Screen out arguments that the Supplemental script does not support.
nonflash_related_options=false
for arg in "$@"
do
  if [[ $arg =~ "--unpack" || "--version" == $arg || "--interface" == $arg || "--inventory" == $arg || "--help" == $arg || "-?" == $arg || "-h" == $arg ]]; then
    nonflash_related_options=true
  fi
  if [[ "--silent" == $arg || "-s" == $arg ]]; then
    SILENT_FLAG=true;
  fi
  if [[ $arg =~ "inventory" ]]; then
     inventory_flag=true
  fi
  if [[ $arg == "--discovery" || $arg == "-d" ]]; then
     discovery_flag=true
  fi
done

# Initialize the variable xml_file to the Smart Component's XML file name.
xml_file=$(ls $PWD | grep -e CP[0-9]*.xml)
if [ -z $xml_file ]; then
  echo "Error: Installation not attempted, unmet dependence: No Smart Component XML file found."
  exit 6
fi

isFileReadable $xml_file "XML"

xml_prefix=$(echo $xml_file | sed -e 's/\(.xml\)*$//')
if [ -z "$xml_prefix" ]; then
  echo "Error: Installation not attempted, unmet dependence: Could not extract the prefix of the XML file name from the $xml_file file."
  exit 6
fi

length=0
for arg in "$@"
do
  length=$(($length + 1))
done
length=$(($length - 1))

arg_counter=0
for arg in "$@"
do
  arg_counter=$(($arg_counter + 1))
  # Set the Log-dir flag to true and use the default directory to hold the log file.
  if [[ "-b" == $arg && 1 == $length || "-b" == $arg && $arg_counter == $length ]]; then
    break
  fi
  # Set the Log-dir flag to true and use the user supplied directory to hold the log file.
  if [[ $arg =~ "--log-dir=" ]]; then
    log_dir=$(echo $arg | sed 's/--log-dir=//')
    continue
  fi
  # Capture the logging directory if one is provided by the user, otherwise use the default location.
  if [[ "-b" = $arg || "true" == $log_dir_flag ]]; then
    if [[ $arg =~ "/" && ! $arg =~ "--discovery=" && ! $arg =~ "--log-dir=" && ! $arg =~ "--usexml=" && ! $arg =~ "--unpack=" ]]; then
      log_dir=$arg
      log_dir_flag=false
      continue
    fi
    log_dir_flag=true
    continue
  fi
done

if [[ 5 != $retval ]]; then
  usexml_flag=false
  arg_counter=0
  for arg in "$@"
  do
    arg_counter=$(($arg_counter + 1))
    if [[ "--usexml" == $arg && 1 == $length || "--usexml" == $arg && $arg_counter == $length ]]; then
      usexml_file=$log_dir/"$xml_prefix"_disc.xml
      usexml_flag=true
      break
    fi
    if [[ "-u" == $arg && 1 == $length || "-u" == $arg && $arg_counter == $length ]]; then
      usexml_file=$log_dir/"$xml_prefix"_disc.xml
      usexml_flag=true
      break
    fi
    if [[ "--usexml" == $arg || "true" == $usexml_flag ]]; then
      if [[ "true" == $usexml_flag && $arg =~ "/" ]]; then
        usexml_file=$arg
        break
      fi
      usexml_flag=true
      continue
    fi
    if [[ $arg =~ "--usexml=" ]]; then
      usexml_file=$(echo $arg | sed 's/--usexml=//')
      usexml_flag=true
      break
    fi
    if [[ "-u" == $arg || "true" == $usexml_flag ]]; then
      if [[ "true" == $usexml_flag && $arg =~ "/" && ! $arg =~ "--discovery=" && ! $arg =~ "--log-dir=" && ! $arg =~ "--usexml=" && ! $arg =~ "--unpack=" ]]; then
        usexml_file=$arg
        break
      fi
      usexml_flag=true
      continue
    fi
  done

  if [[ "true" == $usexml_flag ]]; then
    isFileReadable $usexml_file "usexml"
    temp_usexml_file=temp_usexml_"$seconds".log
    cp $usexml_file $temp_usexml_file
    isFileReadable $temp_usexml_file "usexml backup"
    # Remove the contents of the usexml file.
    echo -n "" > $usexml_file
    storcli_marker_flag=true
    # This while loop locates and captures the duration value from the discovery XML file.
    while read -r a_line_from_xml_file
    do
      if [[ $a_line_from_xml_file =~ "PD Location:" ]]; then
        storcli_marker_flag=false
      fi
      if [[ "true" == $storcli_marker_flag ]]; then
        echo $a_line_from_xml_file >> $usexml_file
      fi
      if [[ "</device>" == $a_line_from_xml_file ]]; then
        storcli_marker_flag=true
      fi
    done < $temp_usexml_file
  fi

  isFileExecutable ${PWD}/setup2 "component"

  # Deside whether or not to execute the Supplemental script.
  if [[ "false" == ${found_storcli_supported_drives_flag} || "true" == $nonflash_related_options ]]; then
    # Capture the Smart Components user prompt.
    if [[ "true" == $SILENT_FLAG || "true" == $discovery_flag ||"true" == $nonflash_related_options ]]; then
	smart_component_prompt_str="$(${PWD}/setup2 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13})"
	retval=$?
	consoleOutput "$smart_component_prompt_str"
	exit $retval
    else
	smart_component_prompt_str="$(echo 'N' | ${PWD}/setup2 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13})"
	retval=$?
    	if [[ 6 == $retval ]]; then
		consoleOutput "$smart_component_prompt_str"
      		exit $retval
    	fi
    	# Break up the Smart Component prompt string on newlines and add it into an array.
    	smart_component_prompt_arr=()
    	while read -r line; do
     	smart_component_prompt_arr+=("$line")
    	done <<< "$smart_component_prompt_str"
    	# If the user requests an inventory, don't display the user prompt.
    	printUserPrompt $@
   	# Execute the Smart Component and capture results and remove redundant data.
	results_str="$(echo "$user_response" | ${PWD}/setup2 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13})"
    	retval=$?
    	# Break the Smart Component varible up in an array.
    	smart_component_results_arr=()
    	while read -r line; do
      		smart_component_results_arr+=("$line")
    	done <<< "$results_str"
    	# Print the Smart Component results.
    	delimiter_flag=false
	crop_str="Select which devices to flash [#,#-#,(A)ll,(N)one]"
    	for line_element in "${smart_component_results_arr[@]}"
   	do
      		if [[ $line_element =~ "$crop_str" ]]; then
        		temp="$(echo $line_element | sed 's/^[^>]*>//g' )"
        		echo "$temp"
        		delimiter_flag=true
        		continue
      		fi
      		if [[ "true" == $delimiter_flag ]]; then
        		echo "$line_element"
      		fi
    	done
    fi
    exit $retval
  elif [[ $discovery_flag == "true" ]]; then
    temp_output1=temp_output1_"$seconds".log
    temp_output2=temp_output2_"$seconds".log
    addDelimiter
    # Shasta Discovery part
    # Capture the Smart Components user prompt.
    # if any other invalid or valid argument passed with -d other than filepath will be igonred by shasta
    smart_component_prompt_str="$(${PWD}/setup2 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13})"
    hpsetup1_status=$?
    #Shasta console output manipulation
    if [[ 6 == $hpsetup1_status ]]; then
        consoleOutput "$smart_component_prompt_str"
        exit $hpsetup1_status
    else
        consoleOutputManipulation "$smart_component_prompt_str"
    fi
    #Mesaverde Discovery Starts here
    export hpsetup1_status
    isFileExecutable ${PWD}/supplement "supplement"
    if [[ 0 < $number_of_controllers_present ]]; then
      ${PWD}/supplement $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} $drives
      retval=$?
    else
    	retval=3
    fi
    output "============ Summary ============"
    output "Smart Component Finished"
    output "Exit Status: $retval"
    if [[ 0 == $retval ]]; then
      output "New FW image activated"
      output "Installation successful, no reboot required"
    elif [[ 1 == $retval ]]; then
      output "Reboot needed to activate FW image"
      output "Installation successful, reboot required"
    elif [[ 2 == $retval ]]; then
      output "Installation not attempted, versions match"
    elif [[ 3 == $retval ]]; then
        if [[ $discovery_flag == "true" ]]; then
                output "Device discovery complete"
                output "Update not attempted. All selected devices are either up-to-date or have newer versions installed."
        else
                output "Update not attempted. All selected devices are either up-to-date or have newer versions installed."
        fi

    elif [[ 4 == $retval ]]; then
      output "Installation not attempted, remote target not found"
    elif [[ 5 == $retval ]]; then
      output "Installation not attempted, cancelled by user"
    elif [[ 6 == $retval ]]; then
      output "Installation not attempted, unmet dependence or tool failure"
    elif [[ 7 == $retval ]]; then
      output "Installation attempted, but failed"
    fi
    rm -rf temp* component*
    exit $retval
  else
    temp_output1=temp_output1_"$seconds".log
    temp_output2=temp_output2_"$seconds".log
    if [[ "false" == $usexml_flag ]]; then
      addDelimiter
      echo "Drive discovery in progress..."
      # Copy the contents of the original usexml back to the usexml file.
      smart_component_prompt_str="$(${PWD}/setup2 $internal_disc_option $disc_file_name $silent_option )"
      hpsetup1_status=$?
      export hpsetup1_status
      isFileExecutable ${PWD}/supplement "supplement"
      suppl_str="$(${PWD}/supplement $internal_disc_option $disc_file_name $silent_option )"
      retval=$?
      hpsum_flag=false
      usexml_flag=true
      CropComponentLogFile
      if [[ $SILENT_FLAG == "false" ]]; then
        # Copy the contents of the original usexml back to the usexml file.
        list_device
        if [ ${#device_ids[@]} == 0 ]
        then
          retval=3
          rm $disc_file_name temp* component*
          output "============ Summary ============"
          output "Exit Status: $retval"
          output "Update not attempted. All selected devices are either up-to-date or have newer versions installed."
          #outpurt "================================================================="
          exit $retval
        fi
        #read -p 'Select which devices to flash [#,#-#,(A)ll,(N)one]> ' option
        res=1
        while [[ $res == 1 ]]
        do
          read -p 'Select which devices to flash [#,#-#,(A)ll,(N)one]> ' option
          read_option $option
          res=$?
        done        
        if [[ $option == N  ||  $option == "None" ]]; then
          retval=3 #shasta returns 3 
          rm -f temp* component* $disc_file_name
          output "============ Summary ============"
          output "Exit Status: $retval"
          output "Installation not attempted, cancelled by user"
          output "See log at: /var/cpq/Component.log"
          #output "================================================================="
          exit $ret_value
        else
          read_option $option
          temp_usexml_file=$disc_file_name
          #echo $temp_usexml_file
          rm -f temp* component*
        fi
      else
        temp_usexml_file=$disc_file_name
        rm -rf temp* component*  
      fi
      
    fi
    if [[ "true" == $usexml_flag ]]; then
       #echo "HPSUM or user passing xml file"
       #Copy the contents of the original usexml back to the usexml file.
       usexml_file=$temp_usexml_file
       isFileReadable $usexml_file "usexml"
    fi
    splitxml
    addDelimiter
    usexml_file=$SAC_file_name
    echo "Flashing of the Smart Array Controller Drives in process"
    if [[ $hpsum_flag == "true" ]]; then
      smart_component_prompt_str="$(${PWD}/setup2 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13})"
    else
      smart_component_prompt_str="$(${PWD}/setup2 $usexml_option $usexml_file $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11})"
    fi
    hpsetup1_status=$?
    #shasta console output manipilation    
    if [[ 6 == $hpsetup1_status ]]; then
        consoleOutput "$smart_component_prompt_str"
        exit $hpsetup1_status
    else
        consoleOutputManipulation "$smart_component_prompt_str"
    fi
    #Mesaverde drives flashing starts here
    export hpsetup1_status
    isFileExecutable ${PWD}/supplement "supplement"
    usexml_file=$NSAC_file_name
    if [[ $hpsum_flag == "true" ]]; then
      ${PWD}/supplement $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} $drives
    else
      ${PWD}/supplement $usexml_option $usexml_file $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} $drives
    fi
    retval=$?
    # Print the output from supplement.
    output "============ Summary ============"
    output "Exit Status: $retval"
    output "Smart Component Finished"
    if [[ 0 == $retval ]]; then
      output "New FW image activated"
      output "Installation successful, no reboot required"
    elif [[ 1 == $retval ]]; then
      output "Reboot needed to activate FW image"
      output "Installation successful, reboot required"
    elif [[ 2 == $retval ]]; then
      output "Installation not attempted, versions match"
    elif [[ 3 == $retval ]]; then
      output "Update not attempted. All selected devices are either up-to-date or have newer versions installed."
    elif [[ 4 == $retval ]]; then
      output "Installation not attempted, remote target not found"
    elif [[ 5 == $retval ]]; then
      output "Installation not attempted, cancelled by user"
    elif [[ 6 == $retval ]]; then
      output "Installation not attempted, unmet dependence or tool failure"
    elif [[ 7 == $retval ]]; then
      output "Installation attempted, but failed"
    fi
    rm -rf temp* component* "disc_file.xml" $NSAC_file_name $SAC_file_name
    exit $retval
  fi
else
  output "============ Summary ============"
  output "Exit Status: $retval"
  output "Installation not attempted, cancelled by user"
  output "See log at: /var/cpq/Component.log"
  rm -rf temp* component*
  exit $retval
fi
