#!/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-2026  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}
#CODECS=${CODECS:-h264dec,h264enc,h265dec,h265enc,vc1dec}
CODECS=${CODECS:-h264dec,h264enc,h265dec,h265enc,vc1dec,av1dec,av1enc,vp9dec}

# 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:
slack_setvarfromupstream AMBERVERS DEMOVERS

# Flags:
BUILD_AMBER=${BUILD_AMBER:-YES}

# 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. )
# 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):
# This variable is used in the demo building scripts.
DRI_DRIVERS="nouveau,r100,r200"

# Determine the configuration options for the known architectures:
case $ARCH in
   aarch64)
     # Device driver settings:
     export VULKAN_DRIVERS="virtio,nouveau,swrast,amd,broadcom,freedreno,panfrost" # 'intel' & 'intel_hasvk' are absent on ARM/A64.
     # Previous aarch64 settings (Dec 2024):
     #export GALLIUM_DRIVERS="swrast,virgl,nouveau,r300,svga,radeonsi,r600,freedreno,etnaviv,tegra,vc4,v3d,lima,panfrost,zink"
     # x86_64 settings, minus i915:
     export GALLIUM_DRIVERS="nouveau,r300,r600,svga,radeonsi,softpipe,llvmpipe,virgl,iris,crocus,zink,d3d12"
     # AArch64 additions:
     GALLIUM_DRIVERS+=",freedreno,etnaviv,tegra,vc4,v3d,lima,panfrost" #,swrast - not permissable in mesa 25.1.0
     export VULKAN_LAYERS="device-select,overlay" # This variable doesn't exist in x86 build script. Added for ease.
     export INTELRT="-Dintel-rt=disabled"
     #export SLKARCH_CONFOPTS="-Ddri3=enabled -Dgbm=enabled"
     export SLKARCH_CONFOPTS=" -Dgbm=enabled"
     # mesa.SlackBuild conf options:
     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"

     #
     # Call-out script options:
     #
     # mesa-demos.build:
     # Update the list of demo binaries since we disable gles1 on AArch64:
     export MESA_DEMO_BINS="eglinfo es2_info es2gears_x11 gears glinfo glthreads glxcontexts glxdemo glxgears glxgears_fbconfig glxheads glxinfo glxpbdemo glxpixmap"
     #export SLK_MESADEMOS_CONF_OPTS="--disable-gles1" # no longer valid in mesa 24.3.4

     # mesa-amber.build:
     #export SLK_AMBER_CONF_OPTS="-Ddri3=enabled -Dgbm=enabled"
     export SLK_AMBER_CONF_OPTS=" -Dgbm=enabled"
     ;;
esac

# Extract source:
echo "Unpacking sources..."
#tar xvvf $CWD/${PKGNAM}-${VERSION}.tar.!(*sign|*asc|*sig) || exit 1
tar xf $CWD/${PKGNAM}-[0-9]*.tar.!(*sign|*asc|*sig) || failextract
#tar xvvf $PORTCWD/sources/EXCLUDE/${PKGNAM}-${VERSION}.tar.!(*sign|*asc|*sig) || exit 1

cd $PKGNAM-*/ || failextract
slackhousekeeping

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

# Don't use the system DirectX headers:
rm -f /usr/lib${LIBDIRSUFFIX}/pkgconfig/DirectX-Headers.pc

# 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 \

# "Download" subprojects:
if [ -r $CWD/mesa-subprojects.tar.lz ]; then
  tar xf $CWD/mesa-subprojects.tar.lz || exit 1
fi

# 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-rusticl=true \
   -Dgallium-extra-hud=true \
   -Drust_std=2021 \
   -Dgallium-drivers=$GALLIUM_DRIVERS \
   \
   -Dvulkan-drivers=$VULKAN_DRIVERS \
   -Dvulkan-layers=$VULKAN_LAYERS \
   -Dvideo-codecs="$CODECS" \
   \
   -Dglvnd=enabled \
   -Dllvm=enabled \
   -Dshared-llvm=enabled \
   -Degl=enabled \
   -Dgles1=enabled \
   -Dgles2=enabled \
   \
   -Dopengl=true \
   -Dglx=dri \
   -Dlibunwind=disabled \
   -Dmicrosoft-clc=disabled \
   -Dvalgrind=enabled \
   $INTELRT \
   \
   $SLKARCH_CONFOPTS \
   .. || exit 1

  # If there's no mesa-subprojects.tar.lz in $CWD, let's try to make one:
  # ARM note: this creates an archive within the upstream Slackware tree, but
  # it should already be present.
  if [ ! -r $CWD/mesa-subprojects.tar.lz ]; then
    cd ..
    mkdir -p tmp/subprojects
    for file in subprojects/* ; do
      if [ "$file" -nt "$PKG" ]; then
        cp -a -v $file tmp/subprojects
      fi
    done
    cd tmp
    find . -name ".git*" -exec rm -r "{}" \; 2> /dev/null
    tar cf $CWD/mesa-subprojects.tar subprojects
    plzip -9 $CWD/mesa-subprojects.tar
    cd ..
    rm -r tmp
    cd meson-build
  fi

  # 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 || failinstall
  # 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 )

if [ "$BUILD_AMBER" = "YES" ]; then
cat << EOF
*********************************************************************
** Building Mesa Amber                                             **
*********************************************************************
EOF
   # Adjust for ARM:
   install -vpm644 $CWD/mesa-amber.build $TMPBUILD/
   sed -i 's?$TMP?$TMPBUILD?g' $TMPBUILD/mesa-amber.build
   # 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):
   sed -i 's?^DRI_DRIVERS=.*?DRI_DRIVERS="'${DRI_DRIVERS}'"?g' $TMPBUILD/mesa-amber.build
   # Call the helper script:
   . $TMPBUILD/mesa-amber.build
fi

# Now build/install a small subset of the demos:
if [ "$BUILD_DEMOS" = "YES" ]; then
cat << EOF
*********************************************************************
** Building Mesa Demos                                             **
*********************************************************************
EOF

   # Adjust for ARM:
   install -vpm644 $CWD/mesa-demos.build $TMPBUILD/
   sed -i 's?$TMP?$TMPBUILD?g' $TMPBUILD/mesa-demos.build
   sed -i 's?$ARCH-slackware-linux?${SLK_ARCH_BUILD}?g' $TMPBUILD/mesa-demos.build
   # Call the helper script:
   . $TMPBUILD/mesa-demos.build
fi

# Install documentation:
mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION/
cp -fav \
  CODEOWNERS* README* docs/README* docs/license* docs/relnotes/${VERSION}.* \
  $PKG/usr/doc/$PKGNAM-$VERSION

# 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

# Replace version number with a _ so it doesn't get confused with
# the package name.
export VERSION="$( echo $VERSION | sed 's?-?_?g' )"
export SLACKPACKAGE=$PKGNAM-$VERSION-$ARCH-$BUILD.txz
slackmp         # run makepkg -l y -c n

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