#!/bin/sh
# NPLL Utilities - npll-install: install NPLL to a directory
#
# Copyright (C) 2026 Techflash
#
# Based on gumboot-utils:
# Copyright (C) 2024 Techflash

usage() {
	cat << EOF
Usage: npll-install [INSTALL DIRECTORY]
Install a copy of NPLL to a directory.
If a block device is given, npll-install will try to resolve a mountpoint.
A clone of 'grub-install', and a part of the 'npll-utils' suite.

  -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-install"

. /usr/lib/npll/util.sh

# handle args
while getopts ":Vvh" opt; do
	case ${opt} in
		V)
			version
			;;
		v)
			log "Verbose mode enabled"
			export v=1
			;;
		h)
			usage
			;;
		?)
			error "Invalid option: -${OPTARG}."
			exit 1
			;;
	esac
done


# handle empty string and not given
if [ "$1" = "" ] || { [ "$1" = "-v" ] && [ "$2" = "" ]; } ; then
	usage
fi

starting

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

dir="$1"
if [ "$1" = "-v" ]; then
	dir="$2"
fi


mkdir -p "$dir/bootmii"
paths="/usr/lib/npll/npll_virtvma_physlma_physentry.elf:$dir/npll.elf
/usr/lib/npll/armboot.bin:$dir/bootmii/armboot.bin"

for pathGroup in $paths; do
	src="$(echo "$pathGroup" | cut -d ':' -f1)"
	dst="$(echo "$pathGroup" | cut -d ':' -f2)"

	if [ "$v" = "1" ]; then
		log "copying $src to $dst"
	fi
	if ! cp "$src" "$dst"; then
		error "Error copying files"
		exit 1
	fi
done

log "Successfully installed NPLL to $dir"
