#!/bin/sh
# Create a machine-id when there is none.
#
# Why this is needed: an image must not ship one. /etc/machine-id was the same
# file in every aos image, from the build of the original image (2026-06-10),
# and therefore identical on every machine -- an identifier that dbus, log
# correlation and some licence checks assume to be unique. Under systemd the
# init creates a new one when the file is empty; under s6 nobody does. This
# oneshot closes exactly that gap.
#
# Only when the file is missing or empty -- an existing identifier stays, also
# across reboots.
set -u

ID_FILE=/etc/machine-id
DBUS_FILE=/var/lib/dbus/machine-id

if [ -s "$ID_FILE" ]; then
  exit 0
fi

id=''
# dbus-uuidgen when available: the same format, and dbus knows its own
# expectations best.
if command -v dbus-uuidgen >/dev/null 2>&1; then
  id="$(dbus-uuidgen 2>/dev/null || true)"
fi

# Otherwise the kernel: 32 hex digits without dashes, exactly the format of
# machine-id(5).
if [ -z "$id" ] && [ -r /proc/sys/kernel/random/uuid ]; then
  id="$(tr -d '-' < /proc/sys/kernel/random/uuid)"
fi

if [ -z "$id" ]; then
  echo 'machine-id: could not create an identifier (neither dbus-uuidgen nor /proc/sys/kernel/random/uuid)' >&2
  exit 1
fi

umask 022
printf '%s\n' "$id" > "${ID_FILE}.tmp" || exit 1
mv -f "${ID_FILE}.tmp" "$ID_FILE" || exit 1
echo "machine-id: created a new identifier (${id})"

# /var/lib/dbus/machine-id follows. In the aos images it is a symlink to
# /etc/machine-id -- then there is nothing to do. A real file there would carry
# the old, shared identifier on.
if [ -e "$DBUS_FILE" ] && [ ! -L "$DBUS_FILE" ]; then
  cp -f "$ID_FILE" "$DBUS_FILE" || true
  echo "machine-id: updated ${DBUS_FILE} as well"
fi
