#!/bin/sh
#
# Copyright (c) 2020 David Demelier <markand@malikania.fr>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

PKGNAME=grub
PKGVERSION=2.02
PKGREVISION=1
PKGLICENSE="GPLv3+"
PKGSUMMARY="GNU boot loader"
PKGDOWNLOAD="ftp://ftp.gnu.org/gnu/$PKGNAME/$PKGNAME-$PKGVERSION.tar.xz"
PKGDEPENDS="core/lvm2 dev/bison dev/flex lib/linux-headers"
PKGOPTIONS="LZMA NLS"

: ${CHOST:=$(uname -m)-linux-musl}
: ${CBUILD:=$(uname -m)-linux-musl}
: ${CTARGET:=$(uname -m)-linux-musl}
: ${CC:=gcc}
: ${CFLAGS:=-O2}
: ${CXX:=g++}
: ${CXXFLAGS:=-O2}
: ${LDFLAGS:=}
: ${LIBS:=}
: ${LZMA:=no}
: ${NLS:=yes}

if [ "$LZMA" = "yes" ]; then
	PKGDEPENDS="core/xz $PKGDEPENDS"
	with_lzma="--enable-liblzma"
else
	with_lzma="--disable-liblzma"
fi

if [ "$NLS" = "yes" ]; then
	PKGDEPENDS="core/gettext:build $PKGDEPENDS"
	with_nls="--enable-nls"
else
	with_nls="--disable-nls"
fi

case $(uname -m) in
"x86_64")
	platforms="efi pc"
	;;
esac

build_grub()
{
	mkdir build && pushd build

	CC="$CC" \
	CFLAGS="$CFLAGS" \
	CXX="$CXX" \
	CXXFLAGS="$CXXFLAGS" \
	LDFLAGS="$LDFLAGS" \
	LIBS="$LIBS" \
	../configure \
		--build=$CBUILD \
		--host=$CHOST \
		--target=$CTARGET \
		--prefix=/usr \
		--disable-libzfs \
		--disable-efiemu \
		--disable-werror \
		--with-platform="$1" \
		$with_lzma \
		$with_nls
	make
	make install DESTDIR=$DESTDIR

	popd
	rm -rf build
}

build()
{
	rm -rf $PKGNAME-$PKGVERSION
	tar xvaf $PKGNAME-$PKGVERSION.tar.xz
	pushd $PKGNAME-$PKGVERSION

	for p in $platforms; do
		build_grub $p
	done

	popd
	rm -rf $PKGNAME-$PKGVERSION
}
