#!/bin/bash
shopt -s extglob

# qt5.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter for Slackware ARM.
#
# Copyright 2006-2025 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.

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

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

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

# 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 SLKCFLAGS="-O2" # ${SLKCFLAGS}" # use defaults from Slackkit
           export SLKLDFLAGS="-L/usr/lib${LIBDIRSUFFIX}" ;; # -Wl,-z,relro -Wl,--as-needed -Wl,-z,now";;
        *) export SLKCFLAGS="-O2" ;;
esac

# ARM notes:
# 1. These configuration options result in building for >armv7, therefore must be "no".
#    They are also disabled by default in Slackware x86.
# 2. Slackware ARM does not offer the alsa fallback, so there's no code here to detect
#    the absence of PulseAudio.
#
USE_CODECS=${USE_CODECS:-YES}
SYSTEM_FFMPEG=${SYSTEM_FFMPEG:-YES}
if [ ! "$USE_CODECS" = "NO" ]; then
   CODEC_OPTION="-proprietary-codecs -webengine-proprietary-codecs"
else
   unset CODEC_OPTION
fi

unset FFMPEG_OPTION
if [ -f /var/lib/pkgtools/packages/ffmpeg-[0-9]* ]; then
   if [ "$SYSTEM_FFMPEG" = "YES" ]; then
      echo "*** Building with System FFMPEG **"
       FFMPEG_OPTION="-webengine-ffmpeg"
   fi
 else
   echo "Bootstrap mode: ffmpeg not found, building without it"
fi
if [ -f /var/lib/pkgtools/packages/sqlite-[0-9]* ]; then
   WITH_SQLITE="-system-sqlite"
   WITH_PLUGINSQLITE="-plugin-sql-sqlite"
 else
   unset WITH_SQLITE
   unset WITH_PLUGINSQLITE
   echo "Bootstrap mode: not using system sqlite"
fi

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

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

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

# Fix build with gcc11:
cd qtbase
  zcat $CWD/patches/qt5-qtbase-gcc11.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null
cd qtwebsockets
  zcat $CWD/patches/qt5-qtwebsockets-gcc11.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null
cd qtwebengine
  zcat $CWD/patches/qt5-qtwebengine-gcc11.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

# Fix build with gcc12:
cd qtwebengine/src/3rdparty
  zcat $CWD/patches/qt5-webengine-gcc12.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

# Fix build with ffmpeg-5:
cd qtwebengine/src/3rdparty
  zcat $CWD/patches/qt5-webengine-ffmpeg5.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

# Fix build with gcc15:
cd qtwebengine
  zcat $CWD/patches/qt5-webengine-gcc-15.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

# Fix build with ffmpeg-7:
cd qtwebengine/src/3rdparty/chromium
  zcat $CWD/patches/qt5-webengine-ffmpeg7.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

# Fix build with icu >- 75:
cd qtwebengine/src/3rdparty
  zcat $CWD/patches/qt5-webengine-icu-75.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

# Fix build with recent ninja:
zcat $CWD/patches/qtwebengine.ninja1.12.patch.gz | patch -p1 --verbose || exit 1

# Fix linking with LLVM 19:
cd qttools
  zcat $CWD/patches/0001-Link-against-libclang-cpp.so-instead-of-the-clang-co.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

## Changes for ffmpeg8 (not enough... help is welcome):
#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

# CMake generates wrong -isystem /usr/include compilations flags with Qt5::Gui
# and for it breaks KWin compilation with:
# /usr/include/c++/9.1.0/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
# See also https://bugzilla.redhat.com/1704474
cd qtbase
  zcat $CWD/patches/qt5.qtbase_cmake_isystem_includes.patch.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

############################################################################
# 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/qt5-qtwebengine/tree/rawhide
# https://archlinuxarm.org/packages/aarch64/qt5-webengine/files

# qtwebengine-5.15.2-ninja1.12.patch, ninja1.12-displaykey.patch is from Gentoo.
# https://bugs.gentoo.org/930107
# It's related to the upgrade of ninja-1.12.
pushd qtwebengine/
for pf in \
   qtwebengine-everywhere-src-5.11.3-aarch64-new-stat.patch  \
   qtwebengine-5.15.2-ninja1.12.patch \
   ninja1.12-displaykey.patch \
  ; do auto_apply_patch $PORTCWD/sources/patches/${pf}* || exit 1
done
popd

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

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

# This becomes doubled at points in the build when ninja -j is called whilst
# 4 cores are occupied with the C preprocessor
[ "$SLKPORTARCH" = "arm" ] && export NUMJOBS=-j2
#[ "$SLKPORTARCH" = "aarch64" ] && export NUMJOBS=-j5

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

# Configure:
#
# 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

export CFLAGS="$SLKCFLAGS"
export CXXFLAGS="$SLKCFLAGS"
export OPENSOURCE_CXXFLAGS="$SLKCFLAGS"
export QTDIR=${TMPBUILD}/qt-everywhere-src-*/
export LD_LIBRARY_PATH="${QTDIR}/qtbase/lib:${QTDIR}/qttools/lib:${LD_LIBRARY_PATH}"
export QT_PLUGIN_PATH="${QTDIR}/qtbase/plugins"
# Fedora uses this: it compiles with or without it. Might be useful as a reminder in the
# future.
#   -no-directfb \
./configure -v \
   -confirm-license \
   -opensource \
   -prefix /usr \
   -libdir /usr/lib${LIBDIRSUFFIX} \
   -bindir /usr/lib${LIBDIRSUFFIX}/qt5/bin \
   -sysconfdir /etc/xdg \
   -headerdir /usr/include/qt5 \
   -datadir /usr/share/qt5 \
   -archdatadir /usr/lib${LIBDIRSUFFIX}/qt5 \
   -docdir /usr/doc/qt5-$VERSION \
   -examplesdir /usr/doc/qt5-$VERSION/examples \
   -system-libpng \
   -system-libjpeg \
   ${WITH_SQLITE} \
   -system-zlib \
   -plugin-sql-mysql \
   ${WITH_PLUGINSQLITE} \
   -accessibility \
   -alsa \
   -dbus \
   -glib \
   -icu \
   -opengl \
   -openssl-linked \
   -optimized-qmake \
   -qpa "xcb;wayland" \
   -qt-harfbuzz \
   -verbose \
   -xcb \
   -egl \
   -eglfs \
   -nomake examples \
   -nomake tests \
   -no-mimetype-database \
   -no-separate-debug-info \
   -no-strip \
   -no-use-gold-linker \
   ${CODEC_OPTION} \
   ${FFMPEG_OPTION} \
   ${RELOCATIONS} \
   -no-pch || failconfig

# Build:
echo "***==============***"
echo "***** Building *****"
echo "***==============***"
make -O V=1 VERBOSE=1 $NUMJOBS || make  -O V=1 VERBOSE=1 || failmake
#make -O V=1 VERBOSE=1 $NUMJOBS || make -O VERBOSE=1 V=1 || failmake
#   { export NINJAJOBS="-j1"
#     export NINJAFLAGS="-v -j1"
#     make -O VERBOSE=1 V=1 ;} || failmake

# Install into package framework:
echo "*****=============****"
echo "***** Installing *****"
echo "*****=============****"
make install INSTALL_ROOT=$PKG || failinstall

# Fix internal linking for Qt5WebEngineCore.pc ,
# thanks to Larry Hajali's SBo script:
sed -i \
  -e 's|-Wl,--start-group.* -Wl,--end-group||' \
  -e "s|-L${PWD}/qtwebengine/src/core/api/Release||" \
  $PKG/usr/lib${LIBDIRSUFFIX}/pkgconfig/Qt5WebEngineCore.pc

# 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/' {} \;

# Fix the qmake path in pri file:
sed -i "s,${QTDIR}/qtbase,/usr/lib${LIBDIRSUFFIX}/qt5," \
  $PKG/usr/lib${LIBDIRSUFFIX}/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri

# Install symlinks to the Qt5 binaries in the $PATH:
mkdir -p $PKG/usr/bin
for FILE in $PKG/usr/lib${LIBDIRSUFFIX}/qt5/bin/* ; do
  ln -vfs ../lib${LIBDIRSUFFIX}/qt5/bin/$(basename $FILE) $PKG/usr/bin/$(basename $FILE)-qt5
done

# Set the QT5DIR 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 755 $PKG/etc/profile.d/*

# Add menu entries for all those hidden but great Qt applications:
# Qt5 logo:
mkdir -vpm755 $PKG/usr/share/icons/hicolor/48x48/apps
convert qtdoc/doc/src/images/qt-logo.png  -resize 48x48 $PKG/usr/share/icons/hicolor/48x48/apps/qt5-logo.png
# Assistant icons
install -vpm644 -D qttools/src/assistant/assistant/images/assistant.png $PKG/usr/share/icons/hicolor/32x32/apps/qt5-assistant.png
install -vpm644 -D qttools/src/assistant/assistant/images/assistant-128.png $PKG/usr/share/icons/hicolor/128x128/apps/qt5-assistant.png
# Designer icon
install -vpm644 -D qttools/src/designer/src/designer/images/designer.png $PKG/usr/share/icons/hicolor/128x128/apps/qt5-designer.png
# QDbusViewer icons
install -vpm644 qttools/src/qdbus/qdbusviewer/images/qdbusviewer.png $PKG/usr/share/icons/hicolor/32x32/apps/qt5-qdbusviewer.png
install -vpm644 qttools/src/qdbus/qdbusviewer/images/qdbusviewer-128.png $PKG/usr/share/icons/hicolor/128x128/apps/qt5-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/qt5-linguist.png
done

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

# Add documentation:
mkdir -vpm755 $PKG/usr/doc/$PKGNAM-$VERSION
cp -fav \
  README qtbase/{header*,LGPL_EXCEPTION.txt,LICENSE*} \
  $PKG/usr/doc/$PKGNAM-$VERSION
changelogliposuction ChangeLog $PKGNAM $VERSION # Trim down a "ChangeLog" file
if [ -d $PKG/usr/lib${LIBDIRSUFFIX}/qt5/doc/html ]; then
  ( cd $PKG/usr/doc/$PKGNAM-$VERSION
    ln -vsf ../../lib${LIBDIRSUFFIX}/qt5/doc/html . )
fi

# Sanity check:
[ "$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
