#!/bin/bash

#  helper script: create ROM images for a given system, with GRUB payload
#
#	Copyright (C) 2020 Leah Rowe <info@minifree.org>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# This script assumes that the working directory is the root
# of git or release archive


# TODO: add make -jWHATEVER to "make" command for coreboot
# TODO: check if coreboot supports multi-core building in its build system
[ "x${DEBUG+set}" = 'xset' ] && set -v
set -u -e

if (( $# != 1 )); then
	printf "Usage: ./build retroboot roms boardname\n"
	printf "Example: ./build retroboot roms x230_4mb\n"
	printf "You need to specify exactly 1 argument\n"
	exit 1
fi

board="${1}"

if [ ! -d "resources/coreboot/${board}" ]; then
    printf "build/roms: Target %s does not exist in the retroboot build system. Skipping build.\n" "${board}"
    exit 1
fi

romdir_grub="bin/grub_${board}"
romdir_seabios="bin/seabios_${board}"
romdir_tianocore="bin/tianocore_${board}"
cbdir="coreboot/${board}"
cbfstool="${cbdir}/util/cbfstool/cbfstool"
corebootrom="${cbdir}/build/coreboot.rom"
seavgabiosrom="payload/seabios/seavgabios.bin"
tianocoreelf="payload/tianocore/tianocore.elf"

if [ ! -d "${cbdir}" ]; then
    ./download coreboot
    ./build module crossgcc
    ./build module cbutils
    ./download tianocore
    ./build payload tianocore
fi

if [ ! -d "${cbdir}/util/crossgcc/xgcc/" ]; then
    ./build module crossgcc
fi

romtype="normal"
if [ -f "resources/coreboot/${board}/romtype" ]; then
    romtype="$(cat resources/coreboot/${board}/romtype)"
fi

if [ ! -f "${tianocoreelf}" ]; then
    ./build payload tianocore
fi

if [ ! -f "${seavgabiosrom}" ]; then
    ./build payload seabios
fi

[ -d "${romdir_grub}/" ] || mkdir -p "${romdir_grub}/"
rm -f "${romdir_grub}"/* coreboot.tmp.grub.rom

[ -d "${romdir_seabios}/" ] || mkdir -p "${romdir_seabios}/"
rm -f "${romdir_seabios}"/* coreboot.tmp.seabios.rom

[ -d "${romdir_tianocore}/" ] || mkdir -p "${romdir_tianocore}/"
rm -f "${romdir_tianocore}"/* coreboot.tmp.tianocore.rom

# it is assumed that no other work will be done on the ROM
# after calling this function. therefore this function is "final"
moverom() {
    rompath="$1"
    newrompath="$2"
    cuttype="$3"

    printf "\nCreating new ROM image: %s\n" "${newrompath}"

    if [ "${cuttype}" = "4MiB IFD BIOS region" ]; then
        dd if=${rompath} of=${newrompath} bs=1 skip=$[$(stat -c %s ${rompath}) - 0x400000] count=4194304
    else
        mv ${rompath} ${newrompath}
    fi

    for romsize in 4 8 16; do
        if [ "${cuttype}" = "${romsize}MiB ICH9 IFD NOR flash" ]; then
            ./build descriptors ich9m
            dd if=descriptors/ich9m/ich9fdgbe_${romsize}m.bin of=${newrompath} bs=1 count=12k conv=notrunc
        fi
    done

    if [ "${cuttype}" = "i945 laptop" ]; then
        dd if=${newrompath} of=top64k.bin bs=1 skip=$[$(stat -c %s ${newrompath}) - 0x10000] count=64k
        dd if=top64k.bin of=${newrompath} bs=1 seek=$[$(stat -c %s ${newrompath}) - 0x20000] count=64k conv=notrunc
        rm -f top64k.bin
    fi
}

for displaymode in vesafb txtmode; do
    for initmode in libgfxinit vgarom; do

        cbcfgpath="resources/coreboot/${board}/config/${initmode}_${displaymode}"
        seabioself="payload/seabios/seabios_${initmode}.elf"

        if [ ! -f "${cbcfgpath}" ]; then
            printf "\nCoreboot config %s_%s for target %s does not exist in the build system. Skipping build.\n" \
                "${initmode}" "${displaymode}" "${board}"
            continue
        fi
        if [ ! -f "${cbfstool}" ]; then
            ./build module cbutils
        fi
        if [ ! -f "${seabioself}" ]; then
            ./build payload seabios
        fi

        (
            cd "${cbdir}"
            make distclean
        )
        cp "${cbcfgpath}" "${cbdir}"/.config
        
        (
            cd "${cbdir}"
            make
        )

        if [ "${displaymode}" = "txtmode" ]; then
            if [ ! -f "memtest86plus/memtest.bin" ]; then
                ./build module memtest86plus
            fi
            "${cbfstool}" "${corebootrom}" add-payload -f memtest86plus/memtest.bin -n img/memtest.bin -c lzma
        fi

        cp "${corebootrom}" coreboot.tmp.seabios.rom
        "${cbfstool}" coreboot.tmp.seabios.rom add-payload -f "${seabioself}" -n fallback/payload -c lzma
        "${cbfstool}" coreboot.tmp.seabios.rom add-int -i 3000 -n etc/ps2-keyboard-spinup
        if [ "${initmode}" = "libgfxinit" ]; then
            "${cbfstool}" coreboot.tmp.seabios.rom add -f "${seavgabiosrom}" -n vgaroms/seavgabios.bin -t raw
        fi

        newrompath="${romdir_seabios}/seabios_${board}_${initmode}_${displaymode}.rom"
        moverom "coreboot.tmp.seabios.rom" "${newrompath}" "${romtype}"

        # tianocore requires vesa framebuffer. will not work in text mode
        if [ "${displaymode}" = "vesafb" ] && \
                [ ! -f "resources/coreboot/${board}/x86_32" ]; then
                # do not include on 32-bit-only machines. this is 64-bit tianocore

            newrompath="${romdir_tianocore}/tianocore_${board}_${initmode}_${displaymode}.rom"
            cp "${corebootrom}" coreboot.tmp.tianocore.rom
            "${cbfstool}" coreboot.tmp.tianocore.rom add-payload -f ${tianocoreelf} -n fallback/payload -c lzma
            moverom "coreboot.tmp.tianocore.rom" "${newrompath}" "${romtype}"

            # also copy it to the generic ROM, which will have GRUB added
            "${cbfstool}" "${corebootrom}" add-payload -f ${tianocoreelf} -n tianocore.elf -c lzma
        fi

        "${cbfstool}" "${corebootrom}" add-payload -f "${seabioself}" -n seabios.elf -c lzma

        if [ "${initmode}" = "libgfxinit" ]; then
            "${cbfstool}" "${corebootrom}" add -f "${seavgabiosrom}" -n vgaroms/seavgabios.bin -t raw
        fi

        "${cbfstool}" "${corebootrom}" add-int -i 3000 -n etc/ps2-keyboard-spinup

        for keymapfile in resources/grub/keymap/original/*; do
            if [ ! -f "${keymapfile}" ]; then
                continue
            fi
            keymap="${keymapfile##*/}"

            grubelf="payload/grub/grub_${keymap}.elf"
            grubcfg="payload/grub/grub_${keymap}_${displaymode}.cfg"
            grubtestcfg="payload/grub/grub_${keymap}_${displaymode}_test.cfg"

            if [ ! -f "${grubelf}" ] || [ ! -f "${grubcfg}" ] \
                || [ ! -f "${grubtestcfg}" ]; then
                ./build payload grub
            fi

            cp "${corebootrom}" coreboot.tmp.grub.rom
            "${cbfstool}" coreboot.tmp.grub.rom add-payload -f "${grubelf}" -n fallback/payload -c lzma
            "${cbfstool}" coreboot.tmp.grub.rom add -f "${grubcfg}" -n grub.cfg -t raw
            "${cbfstool}" coreboot.tmp.grub.rom add -f "${grubtestcfg}" -n grubtest.cfg -t raw

            if [ "${displaymode}" = "vesafb" ]; then
                "${cbfstool}" coreboot.tmp.grub.rom add -f resources/grub/font/dejavusansmono.pf2 -n dejavusansmono.pf2 -t raw
            fi

            newrompath="${romdir_grub}/grub_${board}_${initmode}_${displaymode}_${keymap}.rom"
            moverom "coreboot.tmp.grub.rom" "${newrompath}" "${romtype}"
        done

    done
done

rm -f coreboot.tmp.{tianocore,seabios,grub}.rom

printf "\nDone! Your ROMs are in bin/\n\n"

