#!/usr/bin/sh
#########################################################
# Orbital Net UBNT Radio Firmware Update Tool           #
# (c) 2024 Orbital Net Ltd                              #
# Author: Andrew Cassidy <andrew.cassidy@orbital.net>   #
#########################################################

if [ -e /tmp/firmware.lock ]; then
  echo "Firmware update already in progress, exiting."
  exit 1
fi

current_firmware=$(grep VERSION: /etc/motd | cut -f 2 -d ':' | tr -d ' ')
wget -O /tmp/firmware.md5sum http://ubntrepo.orbitalgroup.com/firmware.md5sum

if grep "$current_firmware" /tmp/firmware.md5sum; then
  echo "Firmware up to date, exiting."
else
  model=$(echo "$current_firmware" | cut -d '.' -f 1)
  filename=$(grep "$model" /tmp/firmware.md5sum | cut -d '/' -f 2)
  if [ "$filename" != "" ]; then
    echo "Firmware update available, downloading..."
    wget -O /tmp/fwupdate.bin "http://ubntrepo.orbitalgroup.com/$filename"
    echo "Updating firmware..."
    touch /tmp/firmware.lock
    /usr/bin/ubntbox fwupdate.real -m /tmp/fwupdate.bin 2>&1 &
    exit 1
  else
    echo "Model $model not recognised, exiting."
  fi
fi
