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

# sddm.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter for Slackware ARM.
#
# Copyright 2015, 2016, 2017, 2018, 2019, 2020  Eric Hameleers, Eindhoven, NL
# Copyright 2024-2025  Patrick J. Volkerding, Sebeka, Minnesota, 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

# 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

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

# Apply patches:
# Don't source $HOME/.xession in SDDM's Xsession script. It may cause the
# wrong session type to launch, or run a second copy of dbus-run-session which
# will break logout:
cat $CWD/sddm.do.not.source.HOME.xsession.diff | patch -p1 --verbose || exit 1

# List Wayland sessions after X11 sessions since Wayland is more experimental:
cat $CWD/sddm.list.X11.sessions.before.Wayland.Sessions.diff | patch -p1 --verbose || exit 1

# Properly inherit the environment instead of hardcoding it:
cat $CWD/sddm.env.insert.patch | patch -p1 --verbose || exit 1

# Switch to the most recently started Xorg server in sddm's
# Xsession script:
cat $CWD/sddm.Xsession.switch.to.newest.Xorg.server.diff | patch -p1 --verbose || exit 1

# Allow build to use CMake 4.x:
export CMAKE_POLICY_VERSION_MINIMUM=3.5

# Configure:
mkdir cmake-build
pushd cmake-build
cmake \
   -DCMAKE_BUILD_TYPE=Release \
   -DCMAKE_C_FLAGS:STRING="$SLKCFLAGS" \
   -DCMAKE_CXX_FLAGS:STRING="$SLKCFLAGS" \
   -DCMAKE_CXX_FLAGS_RELEASE:STRING="$SLKCFLAGS" \
   -DCMAKE_INSTALL_PREFIX=/usr \
   -DCMAKE_INSTALL_MANDIR=/usr/man \
   -DLIB_SUFFIX=${LIBDIRSUFFIX} \
   -DBUILD_MAN_PAGES:BOOL=TRUE \
   -DDBUS_CONFIG_FILENAME="org.freedesktop.sddm.conf" \
   -DNO_SYSTEMD:BOOL=TRUE \
   -DUSE_ELOGIND:BOOL=TRUE \
   -DSDDM_INITIAL_VT=7 \
   .. || failconfig

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

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

# Replace systemd-centric files with ours:
rm -f $PKG/etc/pam.d/sddm*
for FILE in sddm sddm-autologin sddm-greeter ; do
  install -Dm644 $CWD/pam.d/$FILE $PKG/etc/pam.d/${FILE}.new
done

# Create the SDDM home directory:
mkdir -vpm755 $PKG/var/lib/sddm

# Remove the sddm.conf file because we will generate our own in the next line:
rm -f $PKG/etc/sddm.conf

# Generate the default sddm.conf:
$PKG/usr/bin/sddm --example-config > $PKG/etc/sddm.conf

# Set the KDE5 theme 'breeze' as default (integrates better with Plasma 5):
sed -i -e "/\[Theme\]/,/^\[/s/^Current.*/Current=breeze/" $PKG/etc/sddm.conf

## Set the rootless X11 as default display:
## NO, don't do this. It isn't reliable, and it's not worth getting paranoid
## over the display manager running as root anyway.
#sed -i 's/DisplayServer=x11/DisplayServer=x11-user/g' $PKG/etc/sddm.conf

# Set GreeterEnvironment for layer-shell-qt:
sed -i 's/GreeterEnvironment=/GreeterEnvironment=QT_WAYLAND_SHELL_INTEGRATION=layer-shell/g' $PKG/etc/sddm.conf

# Set kwin_wayland as compositor command:
sed -i 's/CompositorCommand=weston --shell=kiosk/CompositorCommand=kwin_wayland --drm --no-lockscreen --no-global-shortcuts --locale1/g' $PKG/etc/sddm.conf

# Move the default config file to .new:
mv -fv $PKG/etc/sddm.conf{,.new}

# Make sure that Plasma and SDDM work on older GPUs,
# by forcing Qt5 to use software GL rendering:
cat << "EOF" >> $PKG/usr/share/sddm/scripts/Xsetup
# Make sure that Plasma and SDDM work on older GPUs by forcing Qt5 to use
# software GL rendering if the OpenGL version is not new enough:
OPENGL_VERSION=$(LANG=C glxinfo |grep '^OpenGL version string: ' |head -n 1 |sed -e 's/^OpenGL version string: \([0-9]\).*$/\1/g')
if [ "$OPENGL_VERSION" -lt 2 ]; then
  QT_XCB_FORCE_SOFTWARE_OPENGL=1
  export QT_XCB_FORCE_SOFTWARE_OPENGL
fi
EOF

# Add a wrapper for the sddm binary, to enable a custom environment:
mv -fv $PKG/usr/bin/sddm $PKG/usr/bin/sddm.bin
cat <<"EOT" > $PKG/usr/bin/sddm
#!/bin/sh
# Customized environment (LANG definition):
if [ -f /etc/default/sddm ]; then
  . /etc/default/sddm
fi

# Ensure non-world readable permissions on /var/log/sddm.log:
touch /var/log/sddm.log
chmod 640 /var/log/sddm.log

# Add a timestamp:
date >> /var/log/sddm.log

# Redirect stdout/stderr to /dev/null to avoid polluting a virtual
# console with duplicate log messages:
exec /usr/bin/sddm.bin "$@" 1> /dev/null 2> /dev/null
EOT
chmod 755 $PKG/usr/bin/sddm

# Let's also add an example customization (localization of the UI):
mkdir -vpm755 $PKG/etc/default
echo ". /etc/profile.d/lang.sh" > $PKG/etc/default/sddm.new

# Add documentation:
mkdir -vpm755 $PKG/usr/doc/$PKGNAM-$VERSION
cp -fav \
  CONTRIBUTORS* ChangeLog* INSTALL* LICENSE* README* docs/* \
  $PKG/usr/doc/$PKGNAM-$VERSION
changelogliposuction ChangeLog $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

# Special permissions & ownerships:
chown sddm:sddm $PKG/var/lib/sddm

slackmp         # run makepkg -l y -c n

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