#!/usr/bin/sh
#########################################################
# Orbital Net UBNT Radio Package Installer              #
# (c) 2024 Orbital Net Ltd                              #
# Author: Andrew Cassidy <andrew.cassidy@orbital.net>   #
#########################################################
REPOSITORY_URL="http://ubntrepo.orbitalgroup.com/"

if [ "$1" = "" ]; then
  echo "Usage: $0 [package name]"
  exit 1
fi

if [ -e /tmp/package.lock ]; then
  echo "/tmp/package.lock exists, exiting."
  exit 1
fi

if wget -O /tmp/sums "$REPOSITORY_URL$1.md5sum"; then
  if md5sum -c /tmp/sums; then
    echo "Package $1 is up to date, exiting."
    exit 0
  else
    echo "Checksums failed, downloading package..."
    touch /tmp/package.lock
    if wget -O /tmp/pkg.tar.gz "$REPOSITORY_URL$1.tar.gz"; then
      echo "Download complete. Installing..."
      tar -xzf /tmp/pkg.tar.gz -C /etc/persistent
      echo "Verifying installation..."
      if md5sum -c /tmp/sums; then
        touch /etc/persistent/installed_packages
        packages=$(echo "$1" | cat /etc/persistent/installed_packages - | sort | uniq)
        echo "$packages" > /etc/persistent/installed_packages
        cfgmtd -f /tmp/running.cfg -w -p /etc/
        touch /tmp/reboot-required
        echo "Installation complete. Reboot required."
        rm /tmp/package.lock
        exit 0
      else
        echo "Installation verification failed. Please contact the Technical Team."
        rm /tmp/package.lock
        exit 1
      fi
    else
      echo "Failed to download package $1, exiting."
      rm /tmp/package.lock
      exit 1
    fi
  fi
else
  echo "Unable to download package $1 manifest, exiting."
  exit 1
fi
