#!/bin/sh
# This script is called by ostree/src/libostree/ostree-bootloader-grub2.c
set -e

script_name=$(basename ${0})
new_config_path=${2}
entries_path=$(dirname $new_config_path)/entries

read_config()
{
    config_file=${entries_path}/${1}
    title=""
    initrd=""
    options=""
    linux=""

    while read -r line
    do
        record=$(echo ${line} | cut -f 1 -d ' ')
        value=$(echo ${line} | cut -f 1 -d ' ' --complement)
        case "${record}" in
            "title")
                title=${value}
                ;;
            "initrd")
                initrd=${value}
                ;;
            "linux")
                linux=${value}
                ;;
            "options")
                options=${value}
                ;;
        esac
    done < ${config_file}

    if [ -z "${title}" ]; then
        title="(Untitled)"
    fi
}

populate_menu()
{
    # TODO conditionally add boot/ prefix - if detected boot/ on the same partition as /usr/
    boot_prefix="/boot"

    for config in $(ls ${entries_path}); do
        read_config ${config}
        menu="${menu}menuentry '${title}' {\n"
        menu="${menu}\t linux ${boot_prefix}/${linux} ${options}\n"
        menu="${menu}\t initrd ${boot_prefix}/${initrd}\n"
        menu="${menu}}\n\n"
    done
    # printf seems to be more reliable across shells for special character (\n, \t) evaluation
    printf "$menu" >> ${new_config_path}
}

populate_header()
{
cat > ${new_config_path} <<EOF
# This file was generated by ${script_name}. Do not modify.
serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1
default=boot
timeout=10

EOF
}

generate_grub_cfg()
{
    populate_header
    populate_menu
}

generate_grub_cfg
