#!/bin/sh
# Creates /etc/machine-id when it is missing, empty, "uninitialized" or
# otherwise not 32 lower-case hex digits (machine-id(5)); a valid one stays.
# With /etc read-only the new id is bind-mounted from /run, as systemd does.
f=/etc/machine-id
id=$(cat "$f" 2>/dev/null)
case $id in
'' | *[!0-9a-f]*) ;;
*) [ ${#id} -eq 32 ] && exit 0 ;;
esac

id=$(tr -d '-' </proc/sys/kernel/random/uuid) || exit 1
umask 022
if printf '%s\n' "$id" >"$f.tmp" 2>/dev/null && mv -f "$f.tmp" "$f"; then
	echo "machine-id: new id $id"
else
	rm -f "$f.tmp" 2>/dev/null
	printf '%s\n' "$id" >/run/machine-id || exit 1
	[ -e "$f" ] || exit 1
	mount --bind /run/machine-id "$f" || exit 1
	echo "machine-id: new id $id, bind-mounted from /run/machine-id"
fi

# a real file there would keep the old id
d=/var/lib/dbus/machine-id
if [ -e "$d" ] && [ ! -L "$d" ]; then
	cp -f "$f" "$d" || :
fi
exit 0
