#!/bin/sh

# Version 1.0
#
# Run 'camcontrol devlist -v' & 'gmirror status' and gets the contents in one list
# this script is automatically run when it receives alert that corresponds to it:
# An example alert is:
# Event Id : 400120001
# Alert Message : There is only one boot disk remaining in the mirror.
# Loss of the remaining boot disk will lead to node failure.
#
# There are no arguments

# Logging
LOGFILE=/var/log/remotesupport.log
log() {
    echo `date +"%FT%"T"%z"` $@ >> ${LOGFILE}
    logger -i "" ${@}
}

# The output filename, in the format that gstools expects:
Prefix='IsilonLogs'
GatherType='CAMControlAndGMirrorStatus'
TimeTag=`date "+%Y%m%d-%H%M%S"`
Cluster=`grep "<name>" /etc/ifs/array.xml | awk -F'</?name>' '{print $2}'`
Suffix="txt"
OutputFile="${Prefix}-${GatherType}-${Cluster}-${TimeTag}.${Suffix}"

OutputDir='/var/crash/support/pkg'        #Use this if /ifs is not available
mkdir -p "${OutputDir}"                   #Make sure the local-storage output directory exists

OutputPath=${OutputDir}/${OutputFile}

# Drop error file here if we are unable to proceed with the requested operation:
ErrDir=/var/crash/ESRS/upload/web
ErrFile='CAMControlAndGMirrorStatus-error.log'
ErrPath=${ErrDir}/${ErrFile}
ErrMsg="Cannot perform camcontrol devlist -v or gmirror status on local storage"

# Try run the command:
CMD1="camcontrol devlist -v >>  ${OutputPath}"
echo "${CMD1}"
CmdOutput=`eval "${CMD1}" 2>&1`
Status1=$?

CMD2="gmirror status >>  ${OutputPath}"
echo "${CMD2}"
CmdOutput=`eval "${CMD2}" 2>&1`
Status=$((${Status1}||$?))

isi_gather_info --esrs --re-upload=${OutputPath}

# If the command failed try figure out why and log it.
case ${Status} in
  "0")
    MSG="The camcontrol devlist -v & gmirror status command Succeeded."
    echo ${MSG}
    log "$0: ${MSG}"
    # It succeeded so remove the temp file
    CMD3="rm -rf ${OutputPath}"
    echo "${CMD3}"
    CmdOutput=`eval "${CMD3}" 2>&1`
    ;;
  *)
    echo "The camcontrol devlist -v & gmirror status commands failed"
    if [ ! -f "$OutputPath" ] ; then
      ErrMsg="camcontrol devlist -v & gmirror status command output file $OutputPath does not exist"
      echo "$ErrMsg"
      echo ErrPath is "$ErrPath"
      date > $ErrPath
      echo "$CmdOutput" >> $ErrPath
      echo "$ErrMsg" >> $ErrPath
      #logging
      log "$0: ${ErrMsg}"
      log "$0: exited with: ${Status}"
      exit 1
    fi
    if [ ! -s "$OutputPath" ] ; then
      ErrMsg="camcontrol devlist -v & gmirror status command output file $OutputPath is empty"
      echo "$ErrMsg"
      date > $ErrPath
      echo "$CmdOutput" >> $ErrPath
      echo "$ErrMsg" >> $ErrPath
      #logging
      log "$0: ${ErrMsg}"
      log "$0: exited with: ${Status}"
      exit 1
    fi
esac

#Success!
log "$0: exited with: ${Status}"
exit 0
