#!/bin/sh
# NPLL Utilities - npll-mkconfig: generate a distro-use NPLL config
#
# Copyright (C) 2026 Techflash
#
# Based on gumboot-utils:
# Copyright (C) 2024 Techflash

usage() {
	cat << EOF
Usage: npll-mkconfig [OPTIONS]
Generate a NPLL config file.
A clone of 'grub-mkconfig', and a part of the 'npll-utils' suite.

  -o FILE         output generated config to FILE [default=stdout]
  -h, --help      print this message and exit
  -v              enable verbose mode
  -V, --version   print the version and exit

Report bugs to the GitHub issues page.
EOF
	exit 0
}

export progname="npll-mkconfig"

. /usr/lib/npll/util.sh

# handle args
while getopts ":o:Vvh" opt; do
	case ${opt} in
		o)
			out="$OPTARG"
			log "Writing to file $out"
			exec > "$out"
			;;
		V)
			version
			;;
		v)
			log "Verbose mode enabled"
			export v=1
			;;
		h)
			usage
			;;
		:)
			error "Option -${OPTARG} requires an argument."
			exit 1
			;;
		?)
			error "Invalid option: -${OPTARG}."
			exit 1
			;;
	esac
done

starting

if [ "$(wii-boot-layout)" = "legacy" ]; then
	error "npll-mkconfig cannot be ran on a legacy system, try \`npll-migrate'"
	exit 1
fi

log "reading config"
. /etc/default/npll

log "reading each npll.d entry"
for f in $(echo /etc/npll.d/* | sort); do
	if [ "$v" = "1" ]; then
		log "starting $f"
	fi
	. "$f"
done

