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

# qt6.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter for Slackware ARM.
#
#
# Copyright 2006-2027  Patrick J. Volkerding, Sebeka
# 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.

# Merged some ideas from Alex Sarmardzic's script for qt4 at SlackBuilds.org
# ^^ Modified by Robby Workman <rworkman@slackware.com> for QT4 & KDE4
#
# Modifications 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2023  Eric Hameleers, Eindhoven, NL
# Modifications for qt 5.2.0 2013 by Michael James, AU
# Modifications for qt 5.x by Eric Hameleers, Eindhoven, NL
# Modifications for qt 6.x 2023, 2024 by Eric Hameleers, Eindhoven, NL

# 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

# Temporary build locations:
export TMPBUILD=$TMP/build-$PKGNAM
export PKG=$TMP/package-$PKGNAM
mkpkgdirs # Delete & re-create temporary directories then cd into $TMPBUILD

# Architecture settings:
case $ARCH in
   aarch64) #export SLKCFLAGS="${SLKCFLAGS} -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fPIC"
           #export RELOCATIONS="-no-reduce-relocations"
           export SLKCONFARGS="-DQT_FEATURE_sse2=OFF"
           export SLKCFLAGS="-O2" # ${SLKCFLAGS}" # use defaults from Slackkit
           export SLKLDFLAGS="-L/usr/lib${LIBDIRSUFFIX}" # -Wl,-z,relro -Wl,--as-needed -Wl,-z,now";;
           # The qtquick3dphysics only compiles on a limited set of architectures:
           DO_PHYSX3D="ON" ;;
        *) export SLKCFLAGS="-O2" ;;
esac

# Take from dbuild:
#export NINJAJOBS="${NUMJOBS#-j}"
export NINJAJOBS="${NUMJOBS}"
# Add some verbosity to the build:
export NINJAFLAGS="-v $NUMJOBS"

# Pull build settings from the x86 trunk:
slack_setvarfromupstream VERSION PKGSRC PKGVER USE_CODECS SYSTEM_FFMPEG

# Previously we didn't have a protobuf package in Slackware.
# Now that we do, it's apparently too new to use with Qt6, so let's just
# disable it to get the same features that we previously did.
# Patches would be accepted here. :-)
#PROTOBUF="-DQT_FEATURE_qtprotobufgen=OFF"

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

# GCC 14 "fix":
# It seems this flag doesn't carry through to qtwebengine where most of the
# warnings are, but we'll leave it here anyway.
SLKCFLAGS="$SLKCFLAGS -Wno-error=template-id-cdtor"

# LLVM22 hack:
SLKCFLAGS="$SLKCFLAGS -Wno-error=template-body"

# Use the 'mold' linker:
#LINKEROPT="-DFEATURE_use_mold_linker=ON"
#LINKEROPT="-DFEATURE_use_gold_linker=ON"
# With qt6.8.3, it fails to configure when using the 'mold' linker.
# Therefore, let qt6 figure it out which linker to use.
# We have no shortage of RAM on the primary build server.
unset LINKEROPT

# If we build our own Qt, unset the QT-related environment variables,
# so that a pre-existing Qt will not be picked up and create errors later:
unset QTDIR
unset QT6DIR
NEWPATH="/usr/lib${LIBDIRSUFFIX}/${PKGNAM}/bin"
for elem in $(echo $PATH | cut -d: --output-delimiter=' ' -f1-) ; do
  if ! $(echo "$elem"| grep -q /qt) ; then
    NEWPATH="$NEWPATH:$elem"
  fi
done
export PATH="$NEWPATH"

# If PulseAudio is not found, use the _alsa $TAG and disable it in the build:
if ! pkg-config --exists libpulse 2>/dev/null ; then
  USE_PULSEAUDIO=${USE_PULSEAUDIO:-"OFF"}
  TAG="${TAG}_alsa"
else
  USE_PULSEAUDIO=${USE_PULSEAUDIO:-"ON"}
  TAG=${TAG:-""}
fi

############################################################################
# Apply patches contained within x86 Slackware
############################################################################

# Fix path to mysql header:
cat $CWD/patches/qt5.mysql.h.diff | patch -p1 --verbose || exit 1

# Re-add support for 32bit architectures - Google no longer supports it:
sed -i qtwebengine/src/3rdparty/chromium/BUILD.gn \
  -e 's/target_os != "linux" || /target_os == "linux" || /'
pushd qtwebengine
  # Thanks Debian! See https://salsa.debian.org/qt-kde-team/qt6/qt6-webengine/-/tree/master/debian/patches
  cat $CWD/patches/qt6-webengine_32bit_compressing_files.patch | patch -p1 --verbose || exit 1
popd
cat $CWD/patches/nodejs-allow-32bit.patch | patch -p1 --verbose || exit 1

# Patch header issue that causes the compile to fail with "x11 not defined"
pushd qtwebengine
  cat $CWD/patches/qtwebengine-6.7.0-displaykey-header.patch | patch -p1 --verbose || exit 1
popd

# Fix qdoc with LLVM22:
cat $CWD/patches/qdoc.fix.for.llvm22.patch | patch -p1 --verbose || exit 1

# QDBusMetaObject: ensure custom types are normalized:
pushd qtbase
  cat $CWD/patches/8b54513cdcf62047376a5d27d784ad68a8f235bf.patch | patch -p1 --verbose || exit 1
popd

## Change for ffmpeg8:
#pushd qtwebengine
#  cat $CWD/patches/ffmpeg_aac_bitstream_converter.ffmpeg8.patch | patch -p1 --verbose || exit 1
#  cat $CWD/patches/ffmpeg_common.cc.ffmpeg8.patch | patch -p1 --verbose || exit 1
#popd

## Fix for ffmpeg8:
#pushd qtmultimedia
#  cat $CWD/patches/65b11b9f9.patch | patch -p1 --verbose || exit 1
#popd

############################################################################
# Apply patches for ARM Slackware
############################################################################
# https://src.fedoraproject.org/rpms/qt5-qtbase/tree/rawhide

# Required if 'rpi-userland' package is installed:
#auto_apply_patch $PORTCWD/sources/patches/ftbfs-qt.diff || failpatch

#pushd qtbase
#for pf in \
#   qt5-qtbase-cxxflag.patch  \
#  ; do auto_apply_patch $PORTCWD/sources/patches/${pf}* || exit 1
#done
#popd

# AArch64: https://src.fedoraproject.org/rpms/qt6-qtwebengine/tree/rawhide
# https://archlinuxarm.org/packages/aarch64/qt6-webengine/files
#     qtwebengine-ffmpeg-first_dts.patch \
pushd qtwebengine/
for pf in \
     qtwebengine-aarch64-new-stat.patch \
     qtwebengine-fix-arm-build.patch.xz \
  ; do auto_apply_patch $PORTCWD/sources/patches/${pf}* || failpatch
done

# delete all "toolprefix = " lines from build/toolchain/linux/BUILD.gn, as we
# don't cross-compile. Fixes aarch64 FTBFS
# Source: https://src.fedoraproject.org/rpms/qt6-qtwebengine/raw/rawhide/f/qt6-qtwebengine.spec
sed -i -e '/toolprefix = /d' -e 's/\${toolprefix}//g' \
  src/3rdparty/chromium/build/toolchain/linux/BUILD.gn

popd

#for pf in \
#  ; do auto_apply_patch $PORTCWD/sources/patches/$pf || exit 1
#done

############################################################################

# Use our custom compiler and linker flags:
sed -e "s|^\(QMAKE_CFLAGS_RELEASE.*\)|\1 ${SLKCFLAGS}|" \
  -i qtbase/mkspecs/common/gcc-base.conf || exit 1
sed -e "s|^\(QMAKE_LFLAGS_RELEASE.*\)|\1 ${SLKLDFLAGS}|" \
  -i qtbase/mkspecs/common/g++-unix.conf || exit 1

# As SBOM generation is failing with 6.8.1 (and was newly changed to be ON by
# default, we'll turn it OFF. But we should test in the future to see if it
# starts to work.

# Configure:
export CFLAGS="$SLKCFLAGS"
export CXXFLAGS="$SLKCFLAGS"
export OPENSOURCE_CXXFLAGS="$SLKCFLAGS"
export QTDIR="${TMPBUILD}/qt-everywhere-src-${PKGSRC}"
if [ ! -z "${LD_LIBRARY_PATH}" ]; then
   export LD_LIBRARY_PATH="${QTDIR}/qtbase/lib:${QTDIR}/qttools/lib:${LD_LIBRARY_PATH}"
 else
  export LD_LIBRARY_PATH="${QTDIR}/qtbase/lib:${QTDIR}/qttools/lib"
fi
export QT_PLUGIN_PATH="${QTDIR}/qtbase/plugins"
cmake -S $(pwd) -B build-${PKGNAM} \
   -G Ninja \
   \
   \
   ${SLKCONFARGS} \
   \
   \
   -Wno-dev \
   -DCMAKE_BUILD_TYPE=Release \
   -DCMAKE_C_FLAGS:STRING="$SLKCFLAGS" \
   -DCMAKE_C_FLAGS_RELEASE:STRING="$SLKCFLAGS" \
   -DCMAKE_CXX_FLAGS:STRING="$SLKCFLAGS" \
   -DCMAKE_CXX_FLAGS_RELEASE:STRING="$SLKCFLAGS" \
   -DCMAKE_INSTALL_PREFIX=/usr \
   -DBUILD_qtquick3dphysics:BOOL=${DO_PHYSX3D} \
   -DINSTALL_BINDIR=/usr/lib${LIBDIRSUFFIX}/qt6/bin \
   -DINSTALL_PUBLICBINDIR=/usr/bin \
   -DINSTALL_LIBDIR=/usr/lib${LIBDIRSUFFIX} \
   -DINSTALL_LIBEXECDIR=/usr/lib${LIBDIRSUFFIX}/qt6/bin \
   -DINSTALL_ARCHDATADIR=/usr/lib${LIBDIRSUFFIX}/qt6 \
   -DINSTALL_DATADIR=/usr/share/qt6 \
   -DINSTALL_INCLUDEDIR=/usr/include/qt6 \
   -DINSTALL_MKSPECSDIR=lib${LIBDIRSUFFIX}/qt6/mkspecs \
   -DINSTALL_DOCDIR=/usr/doc/qt6-${PKGVER} \
   -DINSTALL_EXAMPLESDIR=/usr/doc/qt6-${PKGVER}/examples \
   -DFEATURE_libproxy=ON \
   -DFEATURE_openssl_linked=ON \
   -DFEATURE_pulseaudio="${USE_PULSEAUDIO}" \
   -DFEATURE_system_sqlite=ON \
   -DFEATURE_system_xcb_xinput=ON \
   $LINKEROPT \
   -DFEATURE_webengine_proprietary_codecs="${USE_CODECS}" \
   -DFEATURE_webengine_system_ffmpeg="${SYSTEM_FFMPEG}" \
   -DFEATURE_webengine_system_pulseaudio="${USE_PULSEAUDIO}" \
   -DFEATURE_webengine_webrtc_pipewire=ON \
   -DFEATURE_quick3dxr_openxr:BOOL=OFF \
   -DFEATURE_system_openxr:BOOL=OFF \
   -DQT_GENERATE_SBOM=OFF \
   -DQT_BUILD_EXAMPLES=OFF \
   $PROTOBUF \
   || failconfig

# Slackware ARM:
# Removed: -DFEATURE_no_direct_extern_access=ON \
# as it fails to build when forced on.

# Build:
echo "***==============***"
echo "***** Building *****"
echo "***==============***"
cmake --build build-${PKGNAM} $NUMJOBS --verbose || failmake

# Install into package:
echo "*****=============****"
echo "***** Installing *****"
echo "*****=============****"
DESTDIR=$PKG cmake --install build-${PKGNAM} || failinstall

# Fix the path in prl files:
find "$PKG/usr/lib${LIBDIRSUFFIX}" -type f -name '*.prl' \
  -exec sed -i -e '/^QMAKE_PRL_BUILD_DIR/d;s/\(QMAKE_PRL_LIBS =\).*/\1/' {} \;

# Install symlinks to the Qt6 binaries in the $PATH:
mkdir -vpm755 $PKG/usr/bin
pushd $PKG/usr
# Setting INSTALL_PUBLICBINDIR creates user_facing_tool_links.txt files:
find $TMPBUILD/qt-everywhere-src-$PKGSRC/build-${PKGNAM} \
  -mindepth 1 -maxdepth 2 -name user_facing_tool_links.txt \
  | xargs cat | sort | uniq \
  | while read MYINP ; do ln -vfs $MYINP ; done
popd

pushd $PKG/usr/bin
  ln -vsf ../lib${LIBDIRSUFFIX}/qt6/bin/lrelease-pro lrelease-pro-qt6
  ln -vsf ../lib${LIBDIRSUFFIX}/qt6/bin/lrelease lrelease-qt6
  ln -vsf ../lib${LIBDIRSUFFIX}/qt6/bin/lupdate-pro lupdate-pro-qt6
  ln -vsf ../lib${LIBDIRSUFFIX}/qt6/bin/lupdate lupdate-qt6
popd

# Set the QT6DIR variable in the environment:
mkdir -vpm755 $PKG/etc/profile.d
sed -e "s,@LIBDIRSUFFIX@,${LIBDIRSUFFIX},g" $CWD/profile.d/$PKGNAM.sh \
  > $PKG/etc/profile.d/$PKGNAM.sh
sed -e "s,@LIBDIRSUFFIX@,${LIBDIRSUFFIX},g" $CWD/profile.d/$PKGNAM.csh \
  > $PKG/etc/profile.d/$PKGNAM.csh
chmod 0755 $PKG/etc/profile.d/*

# Add menu entries for all those hidden but great Qt applications:
# Qt6 logo:
mkdir -vpm755 $PKG/usr/share/icons/hicolor/{48x48,128x128}/apps
convert qtdoc/doc/src/images/qt-logo.png  -resize 48x48 $PKG/usr/share/icons/hicolor/48x48/apps/qt6-logo.png
convert qtdoc/doc/src/images/qt-logo.png  -resize 128x128 $PKG/usr/share/icons/hicolor/128x128/apps/qt6-logo.png
# Assistant icons
install -vpm644 -D qttools/src/assistant/assistant/images/assistant.png $PKG/usr/share/icons/hicolor/32x32/apps/qt6-assistant.png
install -vpm644 -D qttools/src/assistant/assistant/images/assistant-128.png $PKG/usr/share/icons/hicolor/128x128/apps/qt6-assistant.png
# Designer icon
install -vpm644 -D qttools/src/designer/src/designer/images/designer.png $PKG/usr/share/icons/hicolor/128x128/apps/qt6-designer.png
# QDbusViewer icons
install -vpm644 qttools/src/qdbus/qdbusviewer/images/qdbusviewer.png $PKG/usr/share/icons/hicolor/32x32/apps/qt6-qdbusviewer.png
install -vpm644 qttools/src/qdbus/qdbusviewer/images/qdbusviewer-128.png $PKG/usr/share/icons/hicolor/128x128/apps/qt6-qdbusviewer.png
# Linguist icons
for icon in qttools/src/linguist/linguist/images/icons/linguist-*-32.png ; do
  size=$(echo $(basename ${icon}) | cut -d- -f2)
  install -vpm644 -D ${icon} $PKG/usr/share/icons/hicolor/${size}x${size}/apps/qt6-linguist.png
done

# And the .desktop files too:
mkdir -vpm755 $PKG/usr/share/applications
cat <<EOF > $PKG/usr/share/applications/qt6-designer.desktop
[Desktop Entry]
Name=Qt6 Designer
GenericName=Interface Designer
Comment=Design GUIs for Qt6 applications
Exec=designer6
Icon=qt6-designer
MimeType=application/x-designer;
Terminal=false
Encoding=UTF-8
Type=Application
Categories=Qt;Development;
EOF
cat <<EOF > $PKG/usr/share/applications/qt6-assistant.desktop
[Desktop Entry]
Name=Qt6 Assistant
Comment=Shows Qt6 documentation and examples
Exec=assistant6
Icon=qt6-assistant
Terminal=false
Encoding=UTF-8
Type=Application
Categories=Qt;Development;Documentation;
EOF
cat <<EOF > $PKG/usr/share/applications/qt6-linguist.desktop
[Desktop Entry]
Name=Qt6 Linguist
Comment=Add translations to Qt6 applications
Exec=linguist6
Icon=qt6-linguist
MimeType=text/vnd.trolltech.linguist;application/x-linguist;
Terminal=false
Encoding=UTF-8
Type=Application
Categories=Qt;Development;
EOF
cat <<EOF > $PKG/usr/share/applications/qt6-qdbusviewer.desktop
[Desktop Entry]
Name=Qt6 QDbusViewer
GenericName=Qt6 D-Bus Debugger
Comment=Debug D-Bus applications
Exec=qdbusviewer6
Icon=qt6-qdbusviewer
Terminal=false
Type=Application
Categories=Qt;Development;Debugger;
EOF

# Add documentation:
mkdir -vpm755 $PKG/usr/doc/$PKGNAM-$VERSION
cp -fav \
  README* LICENSE.* \
  qtwebengine/{CHROMIUM_VERSION,LICENSE.Chromium} \
  $PKG/usr/doc/$PKGNAM-$VERSION
find -maxdepth 2 -name LICENSES \
  | xargs -I{} cp -ia --parents {} $PKG/usr/doc/$PKGNAM-$PKGVER/
if [ -d $PKG/usr/lib${LIBDIRSUFFIX}/qt6/doc/html ]; then
   ( cd $PKG/usr/doc/$PKGNAM-$PKGVER
     ln -vsf ../../lib${LIBDIRSUFFIX}/qt6/doc/html . )
fi
#changelogliposuction ChangeLog $PKGNAM $VERSION # Trim down a "ChangeLog" file

# Sanity check:
# Don't know if we'll need this for qt6 - taken from qt5.SB
#[ "$R2BFINALPASS" = "1" ] && {
#   if [ ! -f $PKG/usr/lib${LIBDIRSUFFIX}/cmake/Qt5WebEngineWidgets/Qt5WebEngineWidgetsConfig.cmake ]; then
#      echo "ERROR: qt5webengine support didn't get built."
#      exit 1
#   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           # set standard Slackware file/dir permissions and ownerships
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
