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

# mesa.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter for Slackware ARM.
#

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

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

# Detect whether we're building for /patches:
# This function sets the variable 'SLACKPATCHING'
slack_findpkgstore_is_stablerelease

# *** This always needs to positioned AFTER 'slackset_var_cwds' ****
#
# Versions of bundled packages and names of source archives.
# To save on maintenance, and since we carry the same versions as x86 Slackware,
# let's pull details from the x86 trunk:
slack_setvarfromupstream SRCNAM FOOVER

# Temporary build locations:
shm_tmp # Use /dev/shm if >8GB RAM is available & not mounted 'noexec'
export TMPBUILD=$TMP/build-$PKGNAM
export PKG=$TMP/package-$PKGNAM
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

# Extract source:
tar xf $CWD/$PKGNAM-$VERSION.tar.!(*sign|*asc|*sig)
cd $PKGNAM-*/ || failextract
slackhousekeeping

# Refresh libtool to support latest architectures:
slackupdatelibtool

========== Useful hacks ==================================================

[ "$SLACKPATCHING" = "no" ] && export PKGSERIES=a

# If this build isn't using distcc (usually due to an incompatability), we
# will set the number of parallel build to the local cores -1.
using_distcc || NUMJOBS="-j$(( $( nproc ) -1 ))"

# Delete this section to use the defaults from the slackkit package,
# otherwise override them here.
# Some packages will fail with CFLAGS set.
# Determine the CFLAGS for the known architectures:
# Add -fPIC to CFLAGS:
#case $ARCH in
#   Switching -O2 to -O3 is an example for flag substitution:
#   arm|aarch64) SLKCFLAGS="${SLKCFLAGS/-O2/-O3} -fPIC"
#                export SLKLDFLAGS="-Wl,-z,relro -Wl,--as-needed -Wl,-z,now";;
#   *)           export SLKCFLAGS="-O2" ;;
#esac

# Remove -fPIC from CFLAGS set by slackkit's config
#case $ARCH in
#   aarch64) SLKCFLAGS="${SLKCFLAGS/-fPIC/}";;
#esac

# This is useful:
#if [[ "${ARCH}" =~ (arm|aarch64) ]]; then echo "yes" ; fi
#[[ ! "$( uname -m )" =~ (aarch64) ]] && exit 0

# Switch errors back to warnings:
#find . -type f -iname '*make*' -print0 | xargs -0 sed -i 's?-Werror=?-Wno-error=?g'

# If needing to use a newer version of gcc on an older system (on which the OS' gcc can't be replaced)
# have the linker use rpath and put the gcc runtime libraries into another dir:
#export LDFLAGS=" -Wl,-rpath,/usr/lib${LIBDIRSUFFIX}/newgcc"

# A useful hack for cmake:
# If -fpermissive is added to the CFLAGS at configure time, the big endian test
# fails, so we'll hack it in now.
# -fpermissive is required to allow non-conformant code in gcc 7.1
#grep -Flr -- '-fexceptions' . | xargs sed -i 's?-fexceptions?-fexceptions -fpermissive?g'
#
# Can be useful for looking if hard coded cpu settings are anywhere:
# grep -Er -- '-m(float-abi|arch|cpu)=' .
# grep -Elr -- '-m(float-abi|arch|cpu)=' . | xargs sed -i 's?blahblah??g'
#
# Build:
# Something like this is useful when building inside Scratchbox:
# eval "sed -i 's/^CFLAGS.*=\(.*\)$/CFLAGS = $SLKCFLAGS \1/' Makefile"
# sed -i 's/^CFLAGS.*=\(.*\)$/CFLAGS = '"$SLKCFLAGS"' \1/' Makefile
# sed -i 's/-Werror[^ ]*//g' src/Makefile Makefile
#
# Make relative symlink :
# root@wizbit:/tmp/usr/include# pwd
# -rw-r--r-- 1 root root    0 Mar 23 16:33 SPIRV
# lrwxrwxrwx 1 root root    5 Mar 23 16:33 priv -> SPIRV
#
# ln -rvfs $PKG/usr/include/{SPIRV,pirv}
#
========== Useful hacks ==================================================

===========================================================================
==========meson version ==================================================
===========================================================================

# Configure:
mkdir meson-build
pushd meson-build
export CFLAGS="$SLKCFLAGS"
export CXXFLAGS="$SLKCFLAGS"
meson setup \
   --prefix=/usr \
   --libdir=/usr/lib${LIBDIRSUFFIX} \
   --libexecdir=/usr/libexec \
   --bindir=/usr/bin \
   --sbindir=/usr/sbin \
   --includedir=/usr/include \
   --datadir=/usr/share \
   --mandir=/usr/man \
   --sysconfdir=/etc \
   --localstatedir=/var \
   .. || failconfig

# Build:
"${NINJA:=ninja}" $NUMJOBS || ${NINJA} || failmake

# Install into package:
DESTDIR=$PKG $NINJA install || failinstall
popd

===========================================================================
==========cmake version =================================================
===========================================================================

# Configure:
mkdir cmake-build
pushd cmake-build
cmake \
   -DCMAKE_C_FLAGS="$SLKCFLAGS" \
   -DCMAKE_INSTALL_PREFIX=/usr \
   -DCMAKE_INSTALL_LIBDIR=lib${LIBDIRSUFFIX} \
   -DBUILD_SHARED_LIBS=ON \
   -DDOC_INSTALL_DIR="doc" \
   -DMAN_INSTALL_DIR=/usr/man \
   .. || failconfig

# Build:
make $NUMJOBS || make || failmake

# Install into package:
make install DESTDIR=$PKG || failinstall
popd

===========================================================================
==========autoconf version =================================================
===========================================================================

# Configure:
slack_autotoolsprep
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
   --prefix=/usr \
   --libdir=/usr/lib${LIBDIRSUFFIX} \
   --mandir=/usr/man \
   --docdir=/usr/doc/$PKGNAM-$VERSION \
   --infodir=/usr/info \
   --sysconfdir=/etc \
   --localstatedir=/var/lib \
   --disable-static \
   --host=${SLK_ARCH_HOST} \
   --build=${SLK_ARCH_BUILD} || failconfig

# Only needed for bootstrapping with x-compiler:
#   --target=${SLK_ARCH_TARGET} \

# Build:
make $NUMJOBS || make || failmake

# Install into package framework:
make install DESTDIR=$PKG || failinstall

===========================================================================
===========================================================================

# Wipe the ones that got installed to the OS as well as $PKG:
#pushd $PKG
#find . -name '*.la' | while read lafile ; do rm -fv ${lafile} /${lafile} ; done
#popd

# Add documentation:
mkdir -vpm755 $PKG/usr/doc/$PKGNAM-$VERSION
cp -fav \

  $PKG/usr/doc/$PKGNAM-$VERSION
changelogliposuction ChangeLog $PKGNAM $VERSION # Trim down a "ChangeLog" file
# If the version number in usr/doc isn't the same as $VERSION, and there's only one entry for $PKGNAM
# then we can use a glob:-
changelogliposuction ChangeLog $PKGNAM '*' # Trim down a "ChangeLog" file
changelogliposuction CHANGES $PKGNAM $VERSION # Trim down a "ChangeLog" file

# 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           # set standard Slackware file/dir permissions and ownerships
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
# If you are building more than 1 package in the same script, you need to
# update $PKGNAM *AND* $SLACKPACKAGE so that the package building
# script knows which previous .t?z package to wipe:
# Example:
# export PKGNAM=$PKGNAM-docs
# export SLACKPACKAGE=$PKGNAM-$VERSION-noarch-$BUILD.txz
===========================================================================

slackdesc            # install slack-desc and doinst.sh
slackmp              # run makepkg -l y -c n
#slackmp -p          # run makepkg --prepend -l y -c n

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