# Shared by the kernel-install layout and initrd generator control facilities.

PROFILE_DIR=/usr/share/bootloader-utils/kernel-install
CONFIG_DIR=/etc/kernel/install.conf.d
LAYOUT_LINK="$CONFIG_DIR/10-altlinux-layout.conf"
GENERATOR_LINK="$CONFIG_DIR/05-altlinux-initrd_generator.conf"

# Print the selected mode, the facility's initial state, or "unknown"
# for a path managed by the administrator.
link_status()
{
	local link="$1" initial="$2" target mode
	shift 2
	if [ ! -e "$link" ] && [ ! -L "$link" ]; then
		echo "$initial"
		return
	fi
	target="$(readlink -- "$link")"
	for mode do
		if [ "$target" = "$PROFILE_DIR/$mode.conf" ] && [ -f "$target" ]; then
			echo "$mode"
			return
		fi
	done
	echo unknown
}

generator_status()
{
	link_status "$GENERATOR_LINK" make-initrd dracut
}

check_plugin()
{
	local plugin="/etc/kernel/install.d/50-$1.install"
	if [ ! -e "$plugin" ] && [ ! -L "$plugin" ]; then
		plugin="/usr/lib/kernel/install.d/50-$1.install"
	fi
	if [ ! -f "$plugin" ] || [ ! -x "$plugin" ]; then
		echo_error "The $1 kernel-install plugin is missing or disabled"
		return 1
	fi
}

select_profile()
{
	local target="$PROFILE_DIR/$1.conf"
	if [ ! -f "$target" ]; then
		echo_error "Configuration template is missing: $target"
		return 1
	fi
	if [ -L "$CONFIG" ]; then
		ln -sfT -- "$target" "$CONFIG"
	else
		ln -sT -- "$target" "$CONFIG"
	fi
}

selection_list()
{
	control_list | sed 's/make_initrd/make-initrd/'
}

valid_mode()
{
	local mode
	for mode in $(selection_list); do
		[ "$1" != "$mode" ] || return 0
	done
	echo_error "Invalid mode: $1"
	return 1
}

selection_help()
(
	local mode
	set -f
	for mode in $1; do
		valid_mode "$mode" || return 1
		# control uses mode names as shell variable suffixes internally.
		if [ "$mode" = make-initrd ]; then
			control_help make_initrd | sed 's/^make_initrd:/make-initrd:/'
		else
			control_help "$mode"
		fi
	done
)

control_selection()
{
	local request="$1"
	case "$request" in
		help) selection_help "$(selection_list)" ;;
		'help '*) selection_help "${request#help }" ;;
		list) selection_list ;;
		summary) control_summary ;;
		status) selection_status ;;
		*)
			valid_mode "$request" || return 1
			mkdir -p -- "$CONFIG_DIR" || return 1
			exec 9< "$CONFIG_DIR" || return 1
			flock -x 9 || return 1
			if [ "$(selection_status)" = unknown ]; then
				echo_error "$CONFIG is managed locally"
				return 1
			fi
			set_selection "$request"
			;;
	esac
}
