#!/usr/bin/env sh

# Copyright 2023-2024 Gentoo Authors
# This script is installed by sys-kernel/installkernel, it is executed by
# systemd's kernel-install, NOT by the traditional installkernel. I.e. this
# plugin is run when the systemd USE flag is enabled or
# SYSTEMD_KERNEL_INSTALL=1 is set in the environment.

COMMAND="${1}"
ENTRY_DIR_ABS="${3}"

# this is exported by kernel-install
if [ -z "${KERNEL_INSTALL_MACHINE_ID}" ]; then
	exit 0
fi

if [ "${KERNEL_INSTALL_LAYOUT}" != "bls" ]; then
	exit 0
fi

if [ "${COMMAND}" != "add" ]; then
	exit 0
fi

# If the machine-id dir does not exist (e.g. $ESP/<machine-id>)
# create it. It receives values directly from kernel-install.
# This is the only function of this plugin.
MACHINE_ID_DIR="${ENTRY_DIR_ABS%/*}"
if ! [ -d "${MACHINE_ID_DIR}" ]; then
	if [ "${KERNEL_INSTALL_VERBOSE}" = "1" ]; then
		echo "+mkdir -v -p ${MACHINE_ID_DIR}"
		mkdir -v -p "${MACHINE_ID_DIR}"
	else
		mkdir -p "${MACHINE_ID_DIR}"
	fi
fi
