#!rsc by RouterOS
# RouterOS script: unattended-lte-firmware-upgrade
# Copyright (c) 2018-2021 Christian Hesse <mail@eworm.de>
# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
#
# schedule unattended lte firmware upgrade
# https://git.eworm.de/cgit/routeros-scripts/about/doc/unattended-lte-firmware-upgrade.md

:foreach Interface in=[ / interface lte find ] do={
  :local Firmware;
  :local IntName [ / interface lte get $Interface name ];
  :do {
    :set Firmware [ / interface lte firmware-upgrade $Interface once as-value ];
  } on-error={
    :log debug ("Could not get latest LTE firmware version for interface " . $IntName . ".");
  }

  :if (($Firmware->"installed") != ($Firmware->"latest")) do={
    :log info ("Scheduling LTE firmware upgrade for interface " . $IntName . ".");
    :global LTEFirmwareUpgrade do={
      :global LTEFirmwareUpgrade;
      :set LTEFirmwareUpgrade;
      / system scheduler remove ($1 . "-firmware-upgrade");
      / interface lte firmware-upgrade $1 upgrade=yes;
      :log info ("LTE firmware upgrade finished, waiting for installation before reset.");
      :delay 150s;
      / interface lte at-chat $1 input="AT+RESET";
      :log info ("Reset device, waiting to finish and reconnect.");
    }
    / system scheduler add name=($IntName . "-firmware-upgrade") start-time=startup interval=2s \
      on-event=(":global LTEFirmwareUpgrade; \$LTEFirmwareUpgrade \"" . $IntName . "\";");
  }
}