#!/bin/bash

set -e
#set -x

if [ $(id -u) -ne 0 ]; then
	echo "$0 needs root: please use sudo."
	exit 1
fi

# Source Auxilium (args parser)
. /usr/share/auxilium/auxilium.sh

auxilium_init $(basename $0) -m 'Update Firmware of a device'

auxilium_add nopause -s n -t opt -m 'No pause after firmware was succefully updated'
auxilium_add device -t positional -m 'Device to update (/dev/sdX)'


if [ -f "/usr/share/ferreus-orbit/common.sh" ]; then
	. "/usr/share/ferreus-orbit/common.sh"
elif [ -f "share/common.sh" ] ; then
	. "share/common.sh"
elif [ -e "../share/common.sh" ] ; then
	. "../share/common.sh"
else
	echo "Cannot load common.sh: exiting."
	exit 1
fi

auxilium_parse "$@"

fo_lock

if ! [ -r "${FW_CONF_FILE}" ] ; then
	echo "Cannot find configuration file."
	exit 1
fi

echo "---> Checking $AUXILIUM_ARG_device"
eval $(udevadm info -q property --export ${AUXILIUM_ARG_device})
readonly SMARTCTL_OUTPUT=$(mktemp -t ${FO_SCRIPT}.smartctl.XXXXXX)
if fo_check_raid; then
	did=$(fo_get_did)
	smartctl -i -d megaraid,${did} "$AUXILIUM_ARG_device" > ${SMARTCTL_OUTPUT} || true
else
	smartctl -i "$AUXILIUM_ARG_device" > ${SMARTCTL_OUTPUT} || true
fi
readonly SMARTCTL_VENDOR=$(cat ${SMARTCTL_OUTPUT} | grep -E '^Vendor:' | awk '{print $2}')
readonly SMARTCTL_PRODUCT=$(cat ${SMARTCTL_OUTPUT} | grep -E '^Product:' | awk '{print $2}')
readonly SMARTCTL_REVISION=$(cat ${SMARTCTL_OUTPUT} | grep -E '^Revision:' | awk '{print $2}')
rm -f ${SMARTCTL_OUTPUT}

echo $SMARTCTL_VENDOR $SMARTCTL_PRODUCT $SMARTCTL_REVISION

if [ "${SMARTCTL_VENDOR}" != "SEAGATE" ] ; then
	echo "-> Vendor Unknown"
	exit 0
fi

if [ -z "${SMARTCTL_PRODUCT}" ] ; then
	echo "Cannot find product name."
	exit 0
fi

if [ -z "${SMARTCTL_REVISION}" ] ; then
	echo "Cannot find revision."
	exit 0
fi

readonly NAME=$(cat "$FW_CONF_FILE" | grep "^${SMARTCTL_PRODUCT},"| awk -F',' '{print $2}')
readonly MINVER=$(cat "$FW_CONF_FILE" | grep "^${SMARTCTL_PRODUCT},"| awk -F',' '{print $3}')
readonly FW=$(cat "$FW_CONF_FILE" | grep "^${SMARTCTL_PRODUCT},"| awk -F',' '{print $4}')

if [ -z "${NAME}" ] || [ -z "${MINVER}" ] || [ -z "${FW}" ] ; then
	echo "Disk Model not found"
	exit 0
else
	echo "-> Detected ${NAME}"
fi


if dpkg --compare-versions "${SMARTCTL_REVISION}" lt "${MINVER}" 2>/dev/null ; then
	echo "-> Detected revision ${SMARTCTL_REVISION}, min version is ${MINVER}: upgrading firmware..."
	if ! openSeaChest_Firmware -d ${AUXILIUM_ARG_device} --downloadFW ${FW_DIR}/${FW}; then
	  if fo_check_raid ;then
			did=$(fo_get_did)
			phy= phy=$(cat ${FO_CACHE_FILE_STORCLI}| jq -r '.["PD LIST"][]|select(.DID=='${did}')["EID:Slt"]')
			readonly EID=$(echo ${phy}|cut -d':' -f1)
			readonly Slt=$(echo ${phy}|cut -d':' -f2)
			${STORCLI} /call/e${EID}/s${Slt} download activatenow src=${FW_DIR}/${FW} || true
		fi
	fi
	if [ -z "$AUXILIUM_ARG_nopause" ]; then
  	echo Pausing for 2 secondes
	  sleep 2
	fi
else
	echo "-> Firmware is up-to-date (${SMARTCTL_REVISION}, min version is ${MINVER})."
fi

exit 0
