#!/bin/bash
#
# Update the DLM Agent ON an already-enrolled device (local / Swift).
#
# This UPDATES the agent together with its matching MIL components
# (Moxa Connection Manager, and on MIL 4 also Moxa Edge / moxa-version),
# and KEEPS the device's existing enrollment and credentials — it does NOT
# clear the enrollment token and does NOT touch credentials.
#
# Run it on the device, from this folder:
#     chmod +x update_agent.sh
#     sudo ./update_agent.sh
#
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"
cd "$SCRIPT_DIR"
shopt -s nullglob

# Collect the agent .deb plus its MIL companion packages shipped next to this script.
mapfile -t DEBS < <(find . -maxdepth 2 -name '*.deb' | sort)
if [ "${#DEBS[@]}" -eq 0 ]; then
  echo "ERROR: no .deb packages found next to this script (expected moxa-dlm-agent*.deb and MIL_packages/)."
  exit 1
fi

echo "Updating ${#DEBS[@]} package(s) — agent + MIL components. Enrollment & credentials are preserved:"
printf '  - %s\n' "${DEBS[@]}"

# --- Compatibility guard: refuse a package built for a different MIL / architecture ---
# Derived from the agent .deb itself, so this stays correct in any package variant.
AGENT_DEB="$(printf '%s\n' "${DEBS[@]}" | grep -E '/moxa-dlm-agent_[^/]*\.deb$' | head -n1 || true)"
if [ -n "${AGENT_DEB:-}" ] && command -v dpkg-deb >/dev/null 2>&1; then
  PKG_ARCH="$(dpkg-deb -f "$AGENT_DEB" Architecture 2>/dev/null || true)"
  SYS_ARCH="$(dpkg --print-architecture 2>/dev/null || true)"
  if [ -n "${PKG_ARCH:-}" ] && [ "$PKG_ARCH" != "all" ] && [ "$PKG_ARCH" != "${SYS_ARCH}" ]; then
    echo "ERROR: This update is built for '${PKG_ARCH}', but this device is '${SYS_ARCH}'. Aborting."
    exit 1
  fi
  EXPECTED_MIL_MAJOR=""
  case "$AGENT_DEB" in
    *+deb11*) EXPECTED_MIL_MAJOR=3 ;;
    *+deb13*) EXPECTED_MIL_MAJOR=4 ;;
  esac
  if [ -n "$EXPECTED_MIL_MAJOR" ] && command -v mx-ver >/dev/null 2>&1; then
    MIL_VER="$(mx-ver -M 2>/dev/null | tr -d '[:space:]')"
    DEV_MIL_MAJOR="${MIL_VER%%.*}"
    if [ -n "${DEV_MIL_MAJOR:-}" ] && [ "$DEV_MIL_MAJOR" != "$EXPECTED_MIL_MAJOR" ]; then
      echo "ERROR: This update is for MIL ${EXPECTED_MIL_MAJOR}.x, but this device is MIL ${MIL_VER}."
      echo "       Use the MIL${DEV_MIL_MAJOR} update package instead. Aborting."
      exit 1
    fi
  fi
fi

# Install all together so versions stay in sync; apt resolves the order/dependencies.
if command -v apt-get >/dev/null 2>&1; then
  if ! DEBIAN_FRONTEND=noninteractive apt-get install -y "${DEBS[@]}"; then
    echo "apt-get failed; falling back to dpkg + dependency fix..."
    dpkg -i "${DEBS[@]}" || true
    DEBIAN_FRONTEND=noninteractive apt-get -y -o APT::Install-Recommends=false install -f
  fi
else
  dpkg -i "${DEBS[@]}"
fi

systemctl daemon-reload || true
systemctl restart moxa-dlm-agent || true

echo "Update complete. The device keeps its existing enrollment."
echo "Verify with:  mx-dlm-agent status"
exit 0
