#!/bin/sh
set -e

root=''
print=0

for arg; do
  case "${arg}" in
    --root=*)  root="${arg#--root=}" ;;
    --print)   print=1 ;;
    --*)       ;;
  esac
done

## Try systemd's own binary first (as ./build.sh diverts it to *.distrib) - fall back if that fails
"${0}.distrib" "$@" 2>/dev/null && exit 0

f="${root}/etc/machine-id"
id=$( cat "${f}" 2>/dev/null || true )

## Keep a valid one, else try to reuse D-Bus's, failing that fall back to make one (same order as systemd's own binary)
if ! echo "${id}" | grep -qx '[0-9a-f]\{32\}'; then
  id=$( cat "${root}/var/lib/dbus/machine-id" 2>/dev/null || true )

  echo "${id}" | grep -qx '[0-9a-f]\{32\}' \
    || id=$( tr -d '-' < /proc/sys/kernel/random/uuid 2>/dev/null || od -An -N16 -tx1 /dev/urandom | tr -d ' \n' )

  mkdir -p "${root}/etc"
  printf '%s\n' "${id}" > "${f}"
  chmod 0444 "${f}"
fi

[ "${print}" = 0 ] || echo "${id}"
