#!/usr/bin/env sh
# set -x
INSTALL_NOT_ATTEMPTED=3
ARGUS=$@
NARGS=$#
#seconds=$(date +%s)
seconds=`date '+%Y_%m_%d_%H_%M_%S'`
usexml_file=
log_dir=/var/cpq
COMPLOGFILE=$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
silentFlag=0
discoveryFlag=0


for arg in "$@"
do
    case $arg in
        -s|--silent)
            silentFlag=1
            #echo "silent flag enabled"
            shift
        ;;
        -f|--force)
            forceFlag=1
            #echo "force flag enabled"
            shift
        ;;
        -g|--downgrade)
            downgradeFlag=1
            echo "downgrade flag enabled"
            shift
        ;;
        -e|--rewrite)
            rewriteFlag=1
            echo "rewrite flag enabled"
            shift
        ;;
        -h|--help)
            shift
                ;;
        --unpack)
            shift
                ;;
        --version)
            shift
                ;;
        --interface)
            shift
                ;;
        --inventory)
            shift
                ;;
        -d|--discovery)
            discoveryFlag=1
            xmlFile="$2"
            #echo "Discovery flag enabled"
            #echo "Discovery file Path: $xmlFile"
            shift
        ;;
        --default)
          echo "Invalid argument: $1"
        ;;
    esac
done

# Write information to stdout and the log file.
output_CmpLog() {
  if [ 1 -eq $silentFlag ]; then
    echo "$1" >> $COMPLOGFILE
  else
    echo "$1" | tee -a $COMPLOGFILE
  fi
}

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

}

# This function checks to see if the file is readable.
isFileReadable() {
  if [[ ! -r $1 ]]; then
    output_CmpLog "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_CmpLog "Error: Installation not attempted, unmet dependency: Unable to execute $1 file."
  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_CmpLog "Error: The $package failed to install!"
     output_CmpLog "Exit Status: $INSTALL_NOT_ATTEMPTED"
     exit $INSTALL_NOT_ATTEMPTED
   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_CmpLog "Info: You are running on an Debian based distribution!"
  DEBNAME=storcli_*.deb
  #chmod +x ${DEBNAME}
  sudo dpkg -i --force-architecture ${DEBNAME}
else
  output_CmpLog "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.
if [[ -f "/etc/redhat-release" || -f "/etc/SuSE-release" || -f "/etc/SUSE-brand" || -f "/etc/debian_version" ]]; then
#storcli_array=$(find /opt/MegaRAID/ -type f \( -name "storcli64" -o -name "storclio64" -o -name "storcli" \) 2> /dev/null)
  storcli=""
  if [[ -f "/opt/MegaRAID/storcli/storcli64" ]]; then
    storcli="/opt/MegaRAID/storcli/storcli64"
  elif [[ -f "/opt/MegaRAID/storcli/storcli" ]]; then
    storcli="/opt/MegaRAID/storcli/storcli"
  elif [[ -f "/opt/MegaRAID/storcli/storclio64" ]]; then
    storcli="/opt/MegaRAID/storcli/storclio64"
  else
    storcli=""
  fi
else
#storcli_array=$(find /opt/lsi/ -type f \( -name "storcli64" -o -name "storclio64" -o -name "storcli" \) 2> /dev/null)
  storcli=""
  if [[ -f "/opt/lsi/storcli/storcli64" ]]; then
    storcli="/opt/lsi/storcli/storcli64"
  elif [[ -f "/opt/lsi/storcli/storcli" ]]; then
    storcli="/opt/lsi/storcli/storcli"
  elif [[ -f "/opt/lsi/storcli/storclio64" ]]; then
    storcli="/opt/lsi/storcli/storclio64"
  else
    storcli=""
  fi
fi

# Verify that the variable contains an executable file.
if [ ! -x "$storcli" ]; then
  output_CmpLog "Error: Cannot find the storcli utility, please install either the storcli or storcli64 utility."
  output_CmpLog "Script Exiting."
  output_CmpLog "Exit Status: $INSTALL_NOT_ATTEMPTED"
  exit $INSTALL_NOT_ATTEMPTED
fi
}

getCmpXMLANDPrefix() {
local TMP=./tmpfile.txt
local JUNK

# 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 dependency: No Smart Component XML file found."
  exit 6
fi

#CMPVERSION=`grep \<version $xml_file|awk -F = '{print $2}'|awk '{print $1}'|`
#CMPVERSION=`grep \<version $xml_file|awk -F = '{print $2}'|awk '{print $1}'|tr -d '"'`
_DESCRIPT=`grep \<alt_name_xlate\ lang\=\"en\" $xml_file|awk -F '>' '{print $2}'|awk -F '<' '{print $1}'|sed -e 's/\"//g'|tail -n 1`

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
echo $xml_prefix
}

file="unknown"
# Search the specified directory (i.e. $1) for a specific file or file type (i.e. $2).
directory_listing() {
  local TMP=./tmpfile.txt
  local JUNK
  file=""
  file=$(find "$1" -type f -iname "$2" | sed -e 's/^\.\///' 2> /dev/null)  
  number_of_files=$(echo $file | awk ' { print split($0, ARRAY_OF_FILES, "[[:space:]]+") } ')
  # Verify that the file variable is not an empty string.
  if [ 0 -eq $number_of_files ]; then
    output_CmpLog "Error: Could not find any Smart Component XML file, please install at least one Smart Component package and re-run the script."
    output_CmpLog "Script Exiting."
    output_CmpLog "Exit Status: $INSTALL_NOT_ATTEMPTED"
    exit $INSTALL_NOT_ATTEMPTED
  fi
  #_VER=`grep \<version $file|awk -F = '{print $2}'|awk '{print $1}'|tr -d '"'`
  echo `grep \<version $file|awk -F = '{print $2}'|awk '{gsub(/"/, "", $1); print $1}'` > $TMP
  read _VER JUNK < $TMP
  _COMP=`grep \<filename\> $file|awk -F '>' '{print $2}'|awk -F '<' '{gsub(/"/, "", $1); print $1}'`
  _DESCRIPT=`grep \<alt_name_xlate\ lang\=\"en\" $file|awk -F '>' '{print $2}'|awk -F '<' '{print $1}'|sed -e 's/\"//g'|tail -n 1`
  _FILENAME="${_COMP%.*}"
  _XML_PREFIX=$(echo $2 | sed -e 's/\(.xml\)*$//')
  
  output_CmpLog "Run with $NARGS Command Arguments(s): $ARGUS"
  output_CmpLog ""
  output_CmpLog "$_COMP - $_DESCRIPT"
  output_CmpLog "    Component Version: $_VER"
}

getCmpXML() {
  directory_listing "." "[cC][Pp]0*.xml"
}

# Write information to discovery xml file.
printXML() {
  if [ ! -x $1 ]; then
    #echo -e $1 "$2" | tee -a $xmlFile
    echo -e $1 "$2" >> $xmlFile
  else
    #echo "$2" | tee -a $xmlFile
    echo "$2" >> $xmlFile
  fi
}

mergeDisXML() {
  egrep -q -v '<hp_rom_discovery |<alt_name|<version|<takes|<type|<devices|</devices>|<\/hp_rom' $2
  OUT=$?
  egrep -q -v '<hp_rom_discovery |<alt_name|<version|<takes|<type|<devices|</devices>|<\/hp_rom' $3
  OUT1=$?
  if [[ $OUT -eq 0 && $OUT1 -eq 0 ]]; then

    cat > $1 << EOF
      `egrep -v '<\/devices>|<\/hp_rom_discovery>' $2`
      `sed -n "/<device>/,/<\/device>/p" $3`
      `echo '</devices>'`
      `echo '</hp_rom_discovery>'`    
EOF
    #cp $2 $1
  elif [[ $OUT -eq 0 && $OUT1 -eq 1 ]]; then
    cp $2 $1
  elif [[ $OUT -eq 1 && $OUT1 -eq 0 ]]; then
    cp $3 $1
  elif [[ $OUT -eq 1 && $OUT1 -eq 1 ]]; then
    cp $2 $1
  fi
}

main() {
    getCmpXML
    isFileExecutable ${PWD}/setup2
    isFileExecutable ${PWD}/supplement
}

main

#if [[ 0 < $number_of_controllers_present ]]; then
  # Flashing Expander firmware attached to Smart Array controller
  if [ -f ${PWD}/setup2 ]; then
    chmod +x ${PWD}/setup2
    ${PWD}/setup2 $ARGUS
    SA_retval=$?
    if [ 1 -eq $discoveryFlag ];then
      mv $xmlFile $PWD/SA_dis.xml
    fi

    if [ -f "/var/cpq/SA_Component.log" ]; then
      mv "/var/cpq/SA_Component.log" /var/cpq/${_XML_PREFIX}_SACMP_${seconds}.log
    fi
  else
    output_CmpLog "${PWD}/setup2 not found"
  fi

  if [ -f ${PWD}/supplement ]; then
    # Flashing Expander firmware attached to MegaRAID controller
    chmod +x ${PWD}/supplement
    ${PWD}/supplement $ARGUS
    MR_retval=$?
    if [ 1 -eq $discoveryFlag ]; then
      mv $xmlFile $PWD/MR_dis.xml
    fi

    if [ -f "/var/cpq/MR_Component.log" ]; then
      mv "/var/cpq/MR_Component.log" /var/cpq/${_XML_PREFIX}_MRCMP_${seconds}.log
    fi
  else
    output_CmpLog "${PWD}/suplement not found"
  fi

  if [ 1 -eq $discoveryFlag ]; then
    mergeDisXML $xmlFile "$PWD/SA_dis.xml" "$PWD/MR_dis.xml"
    rm "$PWD/SA_dis.xml" "$PWD/MR_dis.xml"
  fi

  if [[ "$SA_retval" -eq "0" && "$MR_retval" -eq "1" ]]; then
    exit $MR_retval  
  elif [[ "$SA_retval" -le "1" && "$MR_retval" -le "3" ]]; then
    exit $SA_retval
  elif [[ "$SA_retval" -le "1" && "$MR_retval" -gt "3" ]]; then
    exit $MR_retval
  elif [[ "$SA_retval" -ge "2"  &&  "$SA_retval" -le "3" ]]  && [[ "$MR_retval" -le "3" ]]; then
    exit $MR_retval
  elif [[ "$SA_retval" -ge "2" && "$SA_retval" -le "3" ]] && [[ "$MR_retval" -gt "3" ]]; then
    exit $MR_retval
  elif [[ "$SA_retval" -gt "3" && "$MR_retval" -le "7" ]]; then
    exit $SA_retval
  fi
