#!/bin/bash

function extract_kernel() {
	iso_file="$1"
	loopback="$(mktemp)"
	7z e -so "$iso_file" boot/grub/loopback.cfg > "$loopback"
	grep -m 1 -o "linux.*vmlinuz" "$loopback" | awk '{ print $2 }'
	rm "$loopback"
}

function extract_initrd() {
	iso_file="$1"
	loopback="$(mktemp)"
	7z e -so "$iso_file" boot/grub/loopback.cfg > "$loopback"
	grep -m 1 -o "initrd.*initrd\S*" "$loopback" | awk '{ print $2 }'
	rm "$loopback"
}

function extract_release() {
	iso_file="$1"
	flavor="$(echo "$iso_file" | cut -d "-" -f 1)"
	number="$(echo "$iso_file" | cut -d "-" -f 2)"
	echo "${flavor^} $number" # ^ capitalizes 1st letter
}

function fill_grub_config_template() {
	iso_file="$1"
	sed_target="$2"
	# copy template line and remove #TEMPLATE\s* in copied line
	sed 's|^#TEMPLATE\s*\(.*\)|\1\n&|g' -i "$sed_target"
	# replace only matches in lines which are not commented out
	sed "/^#/!s|__KERNEL__|$(extract_kernel "$iso_file")|g" -i "$sed_target"
	sed "/^#/!s|__INITRD__|$(extract_initrd "$iso_file")|g" -i "$sed_target"
	sed "/^#/!s|__RELEASE__|$(extract_release "$iso_file")|g" -i "$sed_target"
	sed "/^#/!s|__ISONAME__|$iso_file|g" -i "$sed_target"
}

# image flavors to put in the grub config
# usage after sourcing (modifies grub_template_copy.cfg)
# cp grub_template.cfg grub_template_copy.cfg
# fill_grub_config_template "kubuntu-18.04.1-desktop-amd64.iso" "grub_template_copy.cfg"
# fill_grub_config_template "xubuntu-18.04.1-desktop-amd64.iso" "grub_template_copy.cfg"
# Boot entries for images appear in the same order as they are generated.