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

# qt5.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter for Slackware ARM.
#
# Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020  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
   arm|aarch64) export SLKCFLAGS="${SLKCFLAGS} -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fPIC"
                export SLKCXXFLAGS="${SLKCFLAGS}"
                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
       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:
# Atari ST-style crack depacker to induce extended periods of nostalgia whilst
# awaiting the unpacking of large source archives:
if [ -z "$R2BRUNNING" ]; then
   tar xf $CWD/qt-everywhere-src-$VERSION.tar.!(*sign|*asc|*sig) &
   while [ ! -z "$( jobs | grep -E 'Running.*tar.*xf.*qt-eve.*' )" ]; do
      bgcol=0
      for((pass=0; pass<10; pass++)); do
         for((i=1; i<50; i++)); do
            let bgcol++
            [ $bgcol -gt 8 ] && bgcol=0
            tput setaf $bgcol  # set foreground colour
   #         tput setab $bgcol  # set background colour
            tput ed  # clear to end of screen
            tput rev  # turn on reverse video mode
            tput sc  # save the cursor position
            tput rc  # restore the cursor position
            printf "\tUNPACKING..\t\n"
            printf "\e[48;5;${i}m%${i}s";
         done
      done
   done
   reset
 else
   # Running through the r2b build system, so no noise in the logs please:
   tar xf $CWD/qt-everywhere-src-$VERSION.tar.!(*sign|*asc|*sig)
fi

cd qt-everywhere-src*/ || exit 1
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

# 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

# Fix sandbox functions for glibc-2.33:
pushd qtwebengine
  zcat $CWD/patches/qtwebengine-everywhere-src-5.15.2-%231904652.patch.gz | patch -p1 --verbose || exit 1
popd

# Apply upstream patch to move the wayland socket polling to a separate event
# thread. This greatly improves the behavior of Plasma Wayland sessions, fixing
# (for example) stuttering that was occuring on multimedia applications.
cd qtwayland
  zcat $CWD/patches/24.diff.gz | patch -p1 --verbose || exit 1
cd - 1>/dev/null

############################################################################
# Apply patches for ARM Slackware
############################################################################
# https://src.fedoraproject.org/rpms/qt5-qtbase/tree/rawhide
pushd qtbase
for pf in \
  qt5-qtbase-cxxflag.patch.bz2 \
  ; do auto_apply_patch $PORTCWD/sources/patches/$pf || exit 1
done
popd

# AArch64: https://src.fedoraproject.org/rpms/qt5-qtwebengine/tree/rawhide
#https://src.fedoraproject.org/rpms/qt5-qtwebengine/raw/rawhide/f/qtwebengine-everywhere-src-5.10.0-linux-pri.patch
#https://src.fedoraproject.org/rpms/qt5-qtwebengine/raw/rawhide/f/qtwebengine-everywhere-src-5.15.2-sandbox-time64-syscalls.patch
pushd qtwebengine/
for pf in \
   qtwebengine-everywhere-src-5.11.3-aarch64-new-stat.patch.xz \
   qtwebengine-everywhere-src-5.15.5-sandbox-time64-syscalls.patch.xz \
   qtwebengine-everywhere-src-5.10.0-linux-pri.patch.xz \
   modified-qtwebengine-everywhere-src-5.15.5-SIGSTKSZ.patch.xz \
   qtwebengine-everywhere-src-5.15.6-clone3.patch.xz \
   qtwebengine-opensource-src-5.9.0-no-neon.patch.xz \
  ; 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
export NUMJOBS=-j2

# Configure:
export LDFLAGS="$SLKLDFLAGS"
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"
export NINJAJOBS="$NUMJOBS"

# Fedora uses this: it compiles with or without it. Might be useful as a reminder in the
# future.
#   -no-directfb \
./configure -v \
   \
   \
   QMAKE_CFLAGS_RELEASE="${SLKCFLAGS}" \
   QMAKE_CXXFLAGS_RELEASE="${SLKCXXFLAGS}" \
   QMAKE_LFLAGS_RELEASE="${SLKLDFLAGS}" \
   -platform linux-g++ \
   \
   \
   -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 \
   ${RELOCATIONS} \
   ${CODEC_OPTION} \
   ${FFMPEG_OPTION} \
   -no-pch || failconfig

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

# Install into package framework:
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

# 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
