#!/bin/busybox 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="GPLv30+"
PKGSUMMARY="GNU boot loader"
PKGDOWNLOAD="ftp://ftp.gnu.org/gnu/$PKGNAME/$PKGNAME-$PKGVERSION.tar.xz"
PKGDEPENDS="lvm2 binutils:build bison flex linux-headers"
PKGOPTIONS="LZMA NLS"

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

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

if [ "$NLS" = "yes" ]; then
	PKGDEPENDS="gettext $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 && cd build
	BUILD_CC="$CC" \
	BUILD_CFLAGS="$CFLAGS" \
	BUILD_CXX="$CXX" \
	BUILD_CXXFLAGS="$CXXFLAGS" \
	CC="$CC" \
	CFLAGS="$CFLAGS" \
	CXX="$CXX" \
	CXXFLAGS="$CXXFLAGS" \
	LDFLAGS="$LDFLAGS" \
	LIBS="$LIBS" \
	TARGET_CC="$CC" \
	TARGET_CFLAGS="$CFLAGS" \
	TARGET_CXX="$CXX" \
	TARGET_CXXFLAGS="$CXXFLAGS" \
	../configure \
		--build=$CBUILD \
		--host=$CHOST \
		--target=$CTARGET \
		--prefix= \
		--sbindir=/bin \
		--disable-werror \
		$with_lzma \
		$with_nls \
		"$@"
	make
	make install DESTDIR=$DESTDIR

	cd ..
	rm -rf build
}

build()
{
	rm -rf $PKGNAME-$PKGVERSION
	tar xvf $PKGNAME-$PKGVERSION.tar.xz
	cd $PKGNAME-$PKGVERSION

	if [ "$CC" = "clang" ]; then
		patch -p0 < ../patch-clang.patch
	fi

	for p in $platforms; do
		case $p in
		efi)
			build_grub --with-platform=$p --disable-efiemu
			;;
		*)
			build_grub --with-platform=$p
			;;
		esac
	done

	cd ..
	rm -rf $PKGNAME-$PKGVERSION
}
