#!/bin/bash
#ulimit -s unlimited
shopt -s extglob

# mesa.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter <mozes@slackware.com>
#
# Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021  Patrick J. Volkerding, Sebeka, MN, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Record toolchain & other info for the build log:
slackbuildinfo

BUILD_DEMOS=${BUILD_DEMOS:-YES}

# Paths to skeleton port's source & x86_64 Slackware source tree:
slackset_var_cwds

# To save on maintenance, and since we carry the same versions as x86 Slackware,
# let's pull the version numbers from the x86 trunk:
XSB=$CWD/$PKGNAM.SlackBuild
[ ! -x $XSB ] && { echo "ERROR: Cannot find x86 SlackBuild for ${PKGNAM}!" ; exit 1; }
for upstreamvar in \
  DEMOVERS \
  ; do
  eval $( egrep "^${upstreamvar}=" $XSB  )
  echo "Upstream variable: ${upstreamvar} version $( eval $( echo "echo \$${upstreamvar}" ) )"
done

# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
#export PKG=$TMP/package-$PKGNAM

# *********
# ** Note** This is stored into /tmp so that xorg can find it (although I don't think it needs to any more)
# *********
export PKG=/tmp/package-mesa
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

# Be sure this list is up-to-date:
# ( "sis" driver doesn't compile on ARM. )
# Original list for Mesa :
#DRI_DRIVERS="i915,i965,r100,r200,nouveau"
#GALLIUM_DRIVERS="nouveau,r300,r600,svga,radeonsi,swrast,virgl,swr,iris,crocus,zink"
# Slackware x86's DRI list (i915 & i965 require libdrm_intel which won't build on ARM, so we need to remove
# them from the list):
DRI_DRIVERS="nouveau,r100,r200"

# Determine the configuration options for the known architectures:
case $ARCH in
   arm|aarch64)
     export GALLIUM_DRIVERS="swrast,virgl,r300,nouveau" # Included in x86 (minus those that don't build - see above)
     # Extra drivers for ARM:
     export GALLIUM_DRIVERS="${GALLIUM_DRIVERS},freedreno,etnaviv,tegra,vc4,v3d,kmsro,lima,panfrost,zink"
     #export SLKARCH_CONFOPTS=""
     export SLKCFLAGS="$SLKCFLAGS -fexceptions -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS"
     export SLKCXXFLAGS="$SLKCFLAGS"
     export SLKLDFLAGS="-Wl,-z,relro -Wl,--as-needed"
     ;;
esac

# Extract source:
echo "Unpacking sources..."
tar xvvf $CWD/${PKGNAM}-${VERSION}.tar.!(*sign|*asc|*sig) || exit 1

cd $PKGNAM-$VERSION || exit 1
slackhousekeeping

# Let's kill the warning about operating on a dangling symlink:
rm -f src/gallium/state_trackers/d3d1x/w32api

# Apply patches:
#
if /bin/ls $CWD/patches/*.patch 1> /dev/null 2> /dev/null ; then
  for patch in $CWD/patches/*.patch ; do
     patch -p1 --verbose < $patch || exit 1 ;
  done
fi

# Apply patches from Deborah & Ian (for ARM and others)
if [ -f $PORTCWD/sources/mesa*diff* ]; then
    xz -dc $PORTCWD/sources/mesa*diff* | patch -p1
    for i in debian/patches/*diff* ; do
      auto_apply_patch $i || exit 1
    done
fi

# Revert these patches from git (and maybe elsewhere):
if /bin/ls $CWD/patches-revert/*.patch 1> /dev/null 2> /dev/null ; then
  for patch in $CWD/patches-revert/*.patch ; do
    patch -p1 -R --verbose < $patch || exit 1 ;
  done
fi

# Dec 2020: removed as per x86 change:
# This note can be removed later.
#   -Ddri-drivers-path=/usr/lib${LIBDIRSUFFIX}/xorg/modules/dri \

# Configure:
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCXXFLAGS" \
LDFLAGS="$SLKLDFLAGS" \
mkdir meson-build
pushd meson-build
meson setup \
   --prefix=/usr \
   --libdir=lib${LIBDIRSUFFIX} \
   --libexecdir=/usr/libexec \
   --bindir=/usr/bin \
   --sbindir=/usr/sbin \
   --includedir=/usr/include \
   --datadir=/usr/share \
   --mandir=/usr/man \
   --sysconfdir=/etc \
   --localstatedir=/var \
   --buildtype=release \
   -Dplatforms=x11,wayland \
   -Dgallium-opencl=icd \
   -Dgallium-nine=true \
   -Dosmesa=true \
   -Ddri-drivers=$DRI_DRIVERS \
   -Dgallium-drivers=$GALLIUM_DRIVERS \
   \
   -Dvulkan-drivers=swrast \
   -Dvulkan-layers=device-select,intel-nullhw,overlay \
   \
   -Dglvnd=true \
   -Dllvm=enabled \
   -Dshared-llvm=enabled \
   -Dshared-glapi=enabled \
   -Degl=enabled \
   -Dgles1=enabled \
   -Dgles2=enabled \
   \
   -Dopengl=true \
   -Dglx=dri \
   \
   $SLKARCH_CONFOPTS \
   .. || exit 1

  # Build:
#  "${NINJA:=ninja}" $NUMJOBS --verbose || $NINJA --verbose || failmake
  # Without distcc for the time being - it used to work but fails on glapi.
  "${NINJA:=ninja}" --verbose || failmake

  # Install into package:
  DESTDIR=$PKG $NINJA install || exit 1
  # For the demo's - otherwise we have to hack around making them find
  # headers, since Slackware ARM builds remove the existing package prior
  # to build.
  # I didn't like this, so the demo's now look within the compiled mesa source.
  #$NINJA install || exit 1
popd

# Install /etc/drirc as a .new file:
if [ -r $PKG/etc/drirc ]; then
   mv -fv $PKG/etc/drirc $PKG/etc/drirc.new
fi

# Add a default provider for glvnd when the vendor cannot be determined:
( cd $PKG/usr/lib${LIBDIRSUFFIX}
  if [ ! -r libGLX_system.so.0 ]; then
    ln -sf libGLX_mesa.so.0 libGLX_system.so.0
  fi )

# Now build/install a small subset of the demos:
export CWD SLKCFLAGS NUMJOBS PKG
if [ "$BUILD_DEMOS" = "YES" ]; then
( cd $TMPBUILD ; pwd
cat << EOF
*********************************************************************
** Building Mesa Demos                                             **
*********************************************************************
EOF
  rm -rf mesa-demos-$DEMOVERS
  tar xf $CWD/mesa-demos-$DEMOVERS.tar.!(*sign|*asc|*sig) || exit 1
  cd mesa-demos-$DEMOVERS
  slackhousekeeping
  # Let's find mesa's include files within the source dir.
  # Pointing to the compiled mesa source permits a bootstrap where no
  # existing Mesa package is installed, and avoids us doing a 'make install'
  # of Mesa to the build host's filesystem:
  CFLAGS="$SLKCFLAGS -I$( echo $TMPBUILD/mesa-$VERSION/include ) -I/usr/include" \
  CXXFLAGS="$SLKCFLAGS -I$( echo $TMPBUILD/mesa-$VERSION/include ) -I/usr/include" \
  ./configure \
    --prefix=/usr \
    --build=${SLK_ARCH_BUILD} || exit 1
  make $NUMJOBS || make || failmake
  # Install all the demos (including the pointless ones) at first, in a
  # temporary location:
  make install DESTDIR=$PKG/cruft || exit 1
  # Install gears and glinfo, as well as a few other demos:
  mkdir -vpm755 $PKG/usr/bin
  for demo in eglinfo gears glinfo glthreads glxcontexts glxdemo glxgears \
    glxgears_fbconfig glxheads glxinfo glxpbdemo glxpixmap ; do
    mv -fv $PKG/cruft/usr/bin/$demo $PKG/usr/bin
  done
  # Remove cruft:
  rm -rf $PKG/cruft
) || exit 1
fi

# Install documentation:
mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION/html
cp -fav \
  docs/COPYING* docs/relnotes/${VERSION}.html docs/README* docs/GL* \
  $PKG/usr/doc/$PKGNAM-$VERSION
cp -fav docs/*.html $PKG/usr/doc/$PKGNAM-$VERSION/html
rm -f $PKG/usr/doc/$PKGNAM-$VERSION/html/relnotes*.html

# I know this is messy but the Slackware configure options
# for xorg-server looks for Mesa source in here, and it's easier
# to do this than modify the config options:
# Only do this if we're running outside of r2b, or r2b's on its final pass.
if [ "$R2BFINALPASS" = "1" -o -z "$R2BRUNNING" ]; then
   ( cd $TMPBUILD
     echo "Archiving compiled mesa source..."
     # If we need it, x11 builds can find the archive and unpack it:
     # No thanks, it takes about 70 mins to compress on ARM.  We'll leave the
     # distribution polishing scripts to compress that.
     #tar -Ixz -pcf $PORTCWD/${ARCH}_mesa-compiled.tar.xz $PKGNAM-$VERSION )
     rm -f $PORTCWD/${ARCH}_mesa-compiled.tar.*
     tar pcf $PORTCWD/${ARCH}_mesa-compiled.tar $PKGNAM-$VERSION )
 else
   echo "Moving source into /tmp so that x11 builds can find it"
   # Should we have any x11 builds in the r2b build batch, we'll put it there
   # during this build pass so that we keep the wheels turning:
   mv -fv $TMPBUILD/$PKGNAM-$VERSION /tmp/
fi

# Apply generic Slackware packaging policies:
cd $PKG
slackstripall   # strip all .a archives and all ELFs
#slackstriprpaths     # strip rpaths
slack_delete_lafiles # delete usr/lib{,64}/*.la
slackgzpages -i # compress man & info pages and delete usr/info/dir
slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
slackdesc       # install slack-desc and doinst.sh
slackmp         # run makepkg -l y -c n

# Perform any final checks on the package:
cd $PKG
slackhlinks     # search for any hard links
