#!/usr/bin/env bash

set -uoeE pipefail

configDir="/etc/kernel/cmdline.d"
configFile="syslinux/syslinux.cfg"

check_config() {
	local f=$1
	if [ ! -f "$ESP_PATH/$(get_linux "$f" | cut -c 3-)" ]; then
	  echo "ce plm"
		return 1
	fi
	for i in $(get_initrd "$f" | tr ',' ' '); do
	  if [ ! -f "$ESP_PATH/$(echo "$i" | cut -c 3-)" ]; then
		  return 1
	  fi
	done
	return 0
}

err() {
  echo "${@}" >&2
  exit 1
}

get_options() {
	local f=$1
		options=$(awk '/^options/{ $1=""; print $0 }' "$f")
	if [ -z "$options" ]; then
		err "no options detected for $f"
	fi
	echo "$options"
}

get_version() {
	local f=$1
	version=$(awk '/^version/{ print $2 }' "$f")
	if [ -z "$version" ]; then
		err "no version field detected for $f"
	fi
	echo "$version"
}

get_linux() {
	local f=$1
	linux=$(awk '/^linux/{ print ".."$2 }' "$f")
	if [ -z "$linux" ]; then
		err "no kernel field detected for $f"
	fi
	echo "$linux"
}

get_initrd() {
	local f=$1
	initrd=$(awk '/^initrd/{ print ".."$2 }' "$f" | paste -s -d ',')
	if [ -z "$initrd" ]; then
		err "no initrd field detected for $f"
	fi
	echo "$initrd"
}

if ! which syslinux &> /dev/null; then
	exit 0
fi

if [ -z "${ESP_PATH:-}" ]; then
  ESP_PATH=$(bootctl -p || err "cannot detect ESP, check if ESP is mounted on /efi or /boot/efi")
fi

for i in "${configDir}"/*-*.cfg; do
	[ -e "$i" ] || continue
	# shellcheck disable=SC1090
	source "$i"
done

configs=()
# kernel / initrd
for config in "${ESP_PATH}"/loader/entries/*.conf*; do
	if check_config "$config"; then
		configs+=("${config}")
	else
		err "kernel or initrd doesn't exist for $config"
	fi
done


if [ "${#configs[@]}" == "0" ]; then
  err "no valid configs found under $ESP_PATH/loader/entries"
fi

readarray -t vSorted < <(printf '%s\n' "${configs[@]}" | sort -rV)
{
  echo "# automatically generated by update-syslinux"
	echo "UI menu.c32"
	echo "PROMPT 0"
	echo
	echo "MENU TITLE Gardenlinux"
	echo "TIMEOUT $TIMEOUT"
	echo "DEFAULT Linux-$(get_version "${vSorted[0]}")"
	echo
	for v in "${vSorted[@]}"; do
		echo "LABEL Linux-$(get_version "$v")"
		echo " LINUX $(get_linux "$v")"
		echo " APPEND $(get_options "$v")"
		echo " INITRD $(get_initrd "$v")"
		echo
	done
} > "${ESP_PATH}/${configFile}.new"

mv "${ESP_PATH}/${configFile}.new" "${ESP_PATH}/${configFile}"
