#!/bin/bash
#
# Check for Firmware updates
#
# Usage: check-for-firmware-updates [0|1]
#
# Checks for firmware updates that are not already on this server.
#
# Options:
#
# 0 - Create a dashboard message if firmware is available
# 1 - Don't create a dashboard message if firmware is available
#
# Return values:
#
#  1 - Firmware udpate available
#  0 - No new firmware available
# -1 - network error
#
# (C) Copyright 2019, Bogen Communications, Inc. All rights reserved.
#

NQ_PRODUCT=STANDALONE

NQ_VERSION=$(cat /opt/bogen/appliance/VERSION.config)

#echo "$NQ_VERSION"

compare_versions () {
    if [[ $1 == $2 ]]
    then
        #echo "EQUAL"
        return "0"
    fi
    local IFS=.
    local i v1=($1) v2=($2)
    # fill in empty fields with 0s
    for ((i=${#v1[@]}; i<${#v2[@]}; i++))
    do
        v1[i]=0
    done
    for ((i=0; i<${#v1[@]}; i++))
    do
        if [[ -z ${v2[i]} ]]
        then
            # fill in empty fields with 0s
            v2[i]=0
        fi
        if ((10#${v1[i]} > 10#${v2[i]}))
        then
            #echo "GREATER"
            return "1"
        fi
        if ((10#${v1[i]} < 10#${v2[i]}))
        then
            #echo "LESS"
            return "2"
        fi
    done
    return "0"
}




if [ -z "`ssh-keygen -F bogen-ssu.bogen.com`" ];
then
   if [ ! -f ~/.ssh/known_hosts ]; then
     sudo mkdir ~/.ssh
     sudo touch ~/.ssh/known_hosts
   fi
   sudo chown -R www-data:www-data ~/.ssh/known_hosts
   ssh-keyscan -H bogen-ssu.bogen.com >> ~/.ssh/known_hosts 2> /dev/null
fi

rm -f /tmp/NyqFirmware.txt

/usr/local/bin/dash-text -r -t FirmwareErr > /dev/null 2>&1

export SSHPASS="s~jYh6g}zGwb"

sshpass -e sftp -oBatchMode=no -b - ftp_bg_user@bogen-ssu.bogen.com << EOF 2> /tmp/bftperr.txt | grep "^Nyq" > /tmp/NyqFirmware.txt
cd FIRMWARE/$NQ_PRODUCT/LATEST
ls -1
quit
EOF

#cat /tmp/NyqFirmware.txt

if [ ! -s /tmp/NyqFirmware.txt ];
then
   rm -f /tmp/NyqFirmware.txt
   if [ ! -s /tmp/bftperr.txt ];
   then
      echo "0"
   else
      dirnotfound="`grep \"Couldn\'t stat remote file: No such file or directory\" /tmp/bftperr.txt`"
      if [ ! -z "$dirnotfound" ];
      then
         echo "0"
      else
         /usr/local/bin/dash-text -D -S warning -t FirmwareErr -m " - Unable to reach bogen-ssu.bogen.com to check for firmware update" > /dev/null 2>&1
         echo "-1"
      fi
   fi
   rm -f /tmp/bftperr.txt
   exit
fi

rm -f /tmp/bftperr.txt

FOUND_NEW_FW=0
DID_DASH_RM=0

IS_NEW_FIRMWARE="0"

for fname in `cat /tmp/NyqFirmware.txt`
do
   NEW_FW_VER="$(echo $fname | sed -e 's/NyqUpdate-\(.*\).tar.gz/\1/')"  
   compare_versions $NEW_FW_VER $NQ_VERSION
   IS_NEW_FIRMWARE="$?"
done

if [ "$IS_NEW_FIRMWARE" = "1" ];
then
   #echo "New Firmware available for download"
   echo "1"
else
   #echo "Current Firmware is at the latest version"
   echo "0"
fi

rm -f /tmp/NyqFirmware.txt
