#!/bin/sh
#
# Copyright (c) 2019 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=mesa
PKGVERSION=18.3.5
PKGREVISION=1
PKGLICENSE="CUSTOM"
PKGSUMMARY="opensource OpenGL implementation"
PKGDOWNLOAD="https://mesa.freedesktop.org/archive/$PKGNAME-$PKGVERSION.tar.xz"
PKGDEPENDS="dev/meson:build"
PKGOPTIONS="DRM LLVM WAYLAND X"

: ${CC:=clang}
: ${CFLAGS:=-O2}
: ${CXX:=clang++}
: ${CXXFLAGS:=-O2}
: ${LDFLAGS:=}
: ${DRM:=yes}
: ${LLVM:=yes}
: ${WAYLAND:=yes}
: ${X:=yes}

with_platforms=""
with_gallium_drivers="r300,r600,virgl,svga,swrast"
with_vulkan_drivers="intel"

if [ "$DRM" = "yes" ]; then
	with_platforms="drm,$platforms"
fi

if [ "$LLVM" = "yes" ]; then
	PKGDEPENDS="dev/llvm:build $PKGDEPENDS"
	with_llvm="-D llvm=true"
	with_gallium_drivers="radeonsi,$with_gallium_drivers"
	with_vulkan_drivers="amd,$with_vulkan_drivers"
else
	with_llvm="-D llvm=false"
fi

if [ "$WAYLAND" = "yes" ]; then
	with_platforms="wayland,$with_platforms"
fi

if [ "$X" = "yes" ]; then
	with_platforms="x11,$with_platforms"
	with_dri="-D dri3=true"
	with_glx="-D glx=dri"
else
	with_dri="-D dri3=false"
	with_glx="-D glx=disabled"
fi

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

	patch -p0 < ../disable-tls.patch
	# https://git.alpinelinux.org/aports/plain/main/mesa/musl-fix-includes.patch
	patch -p1 < ../musl.patch
	CC="$CC" \
	CFLAGS="$CFLAGS" \
	CXX="$CXX" \
	CXXFLAGS="$CXXFLAGS" \
	LDFLAGS="$LDFLAGS" \
	meson \
		--prefix /usr \
		--buildtype release \
		--default-library shared \
		-D egl=true \
		-D bpm=true \
		-D platforms=$with_platforms \
		-D gallium-drivers=$with_gallium_drivers \
		-D vulkan-drivers=$with_vulkan_drivers \
		$with_llvm \
		$with_dri \
		$with_glx \
		. build
	ninja -C build
	DESTDIR=$DESTDIR ninja -C build install

	popd
	rm -rf $PKGNAME-$PKGVERSION
}

