#!/usr/bin/bash
set -Eeuo pipefail

requested_target_root="${1:-}"
uuidgen="${TUXENIX_DBUS_UUIDGEN:-/usr/bin/dbus-uuidgen}"

case "$requested_target_root" in
    /*) ;;
    *)
        echo "Calamares target root must be an absolute path: ${requested_target_root:-empty}" >&2
        exit 1
        ;;
esac

requested_normalized="$requested_target_root"
while [ "${requested_normalized%/}" != "$requested_normalized" ]; do
    requested_normalized="${requested_normalized%/}"
done

target_root="$(readlink -f -- "$requested_target_root" 2>/dev/null || true)"
if [ -z "$target_root" ] || [ "$target_root" = "/" ] || [ ! -d "$target_root" ]; then
    echo "Invalid Calamares target root: ${requested_target_root:-empty}" >&2
    exit 1
fi
if [ -L "$requested_target_root" ] || [ "$target_root" != "$requested_normalized" ]; then
    echo "Calamares target root must be canonical and must not contain symlink components." >&2
    exit 1
fi
for managed_directory in \
    "$target_root/etc" \
    "$target_root/var" \
    "$target_root/var/lib" \
    "$target_root/var/lib/dbus"; do
    if [ -L "$managed_directory" ]; then
        echo "Refusing to write machine-id through symlinked target path: $managed_directory" >&2
        exit 1
    fi
done
if [ ! -x "$uuidgen" ]; then
    echo "D-Bus UUID generator is missing or not executable: $uuidgen" >&2
    exit 1
fi

install -d -m 0755 "$target_root/etc" "$target_root/var/lib/dbus"

if ! machine_id="$("$uuidgen")"; then
    echo "D-Bus UUID generation failed." >&2
    exit 1
fi
if ! printf '%s\n' "$machine_id" | grep -Eq '^[[:xdigit:]]{32}$'; then
    echo "D-Bus UUID generator returned an invalid machine-id." >&2
    exit 1
fi
machine_id="$(printf '%s' "$machine_id" | tr '[:upper:]' '[:lower:]')"

machine_file="$target_root/etc/machine-id"
machine_tmp="$(mktemp "$target_root/etc/.machine-id.XXXXXX")"
cleanup() {
    rm -f -- "$machine_tmp"
}
trap cleanup EXIT

printf '%s\n' "$machine_id" > "$machine_tmp"
chmod 0444 "$machine_tmp"
mv -f -- "$machine_tmp" "$machine_file"
ln -sfnT /etc/machine-id "$target_root/var/lib/dbus/machine-id"

if [ "$(cat "$machine_file")" != "$machine_id" ] \
    || [ "$(readlink "$target_root/var/lib/dbus/machine-id" 2>/dev/null || true)" != "/etc/machine-id" ]; then
    echo "Installed machine-id verification failed." >&2
    exit 1
fi

trap - EXIT
echo "Generated Tuxenix machine-id with dbus-uuidgen."
