#!/bin/bash
# Private — All rights reserved. © 2026 IACA Electronique.
# Unauthorized use, reproduction, or distribution is strictly prohibited.
#
# Purpose: Renew the unique device identifier of an Optimum Tracker Gateway.

UUID_CTL_SCRIPT=/root/uuid-ctl.sh
UUID_FILE=/etc/iaca/uuid


function unlock_fs(){
  if ! sudo mount -o remount,rw /; then
    return 1
  fi
}

function backup_files(){
  cp "${UUID_FILE}" "${UUID_FILE}.old" && cp "${UUID_CTL_SCRIPT}" "${UUID_CTL_SCRIPT}.old"
}

function override_uuid() {
  local MAC=$(ip -o link show eth0 | awk '{print $17}')
  local IP=$(ip -4 -o addr show eth0 | awk '{print $4}')
  local HASH=$(( RANDOM % 10000 ))

  echo "${MAC}|${IP}#${HASH}" > /etc/iaca/uuid
}

function disable_uuid_ctl() {
    echo -e "#!/bin/bash\nexit 0" > "${UUID_CTL_SCRIPT}"
}

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

unlock_fs || { echo "Unable to unlock FS."; exit 2; }
backup_files || { echo "Unable to backup file."; exit 3; }
override_uuid || { echo "Unable to refresh UUID."; exit 4; }
disable_uuid_ctl || { echo "Unable to disable UUID protection."; exit 5; }

echo "Identifier renewed. Please reboot."

exit 0