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

# seamonkey.SlackBuild
# Heavily based on the original Slackware build scripts,
# Modified by Stuart Winter <mozes@slackware.com>
#
# Copyright 2008-2021  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.

##
## Build note:
## Because this build references the libffi sources from the firefox directory,
## it means that when building it from the 'patches' directory, this doesn't work.

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

# sed 4.2 is needed:https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=850984
#sed --version | head -n1 | grep 4.2 || { echo "need sed 4.2" ; exit 1 ; }

# 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

# Determine the CFLAGS for the known architectures:
#
# -fno-delete-null-pointer-checks disables gcc6 optimization that leads to instability
# -fno-schedule-insns2 don't do an additional pass of instruction scheduling
# -fno-lifetime-dse allow object storage to persist beyond the lifetime of the object
#export CFLAGS="-Wformat -Wno-format-overflow -fno-delete-null-pointer-checks -fno-schedule-insns2"
#export CXXFLAGS="-Wformat -Wno-format-overflow -fno-delete-null-pointer-checks -fno-schedule-insns2 -fno-lifetime-dse -fpermissive"
case $ARCH in
   # arm used to use -O
   arm|aarch64)
            export SLKCFLAGS="-Wformat -fno-delete-null-pointer-checks"
            export SLKCXXFLAGS="-Wformat -fno-delete-null-pointer-checks -fpermissive"
            export OPTIMIZE_FLAG="-O1 -g0"
            # For gold linker:
            #export SLKLDFLAGS="-Wl,--no-keep-memory -Wl,--no-keep-files-mapped -Wl,--no-map-whole-files -Wl,--no-mmap-output-file -Wl,--stats -Wl,--reduce-memory-overhead"
            # bfd linker:
            export SLKLDFLAGS="-Wl,--as-needed -Wl,--no-keep-memory -Wl,--stats -Wl,--reduce-memory-overhead"
            # The little hacks section:
            # Firefox 17.0 adds webrtc but it does not work on ARM
            #SLKCONFARGS="--disable-webrtc"
            #
            # Slackware ARM used to disables ELF hack to make it build, but upstream enables
            # it (as this is apparently what the official Thunderbird binary build has in its configuration):
	    # --disable-elf-hack \
            #export SLKCONFARGS="$SLKCONFARGS \
            #                    --disable-crashreporter \
            #                    --with-system-libvpx \
            #                    --enable-system-ffi" ;;

            ;;

   *)       export SLKCFLAGS="-O2" ;;
esac

# If there is a private Google API key available at compile time, use
# it to enable support for Google Safe Browsing. For Slackware builds,
# we use a private key issued for the Slackware project. If you are
# rebuilding and need this support, or you are producing your own
# distribution, you may obtain your own Google API key at no charge by
# following these instructions:
# https://bugzilla.mozilla.org/show_bug.cgi?id=1377987#c0
if [ -f "$PORTCWD/.GoogleSafeBrowsingAPI_Key" ]; then
   GOOGLE_API_KEY="--with-google-safebrowsing-api-keyfile=$PORTCWD/.GoogleSafeBrowsingAPI_Key"
fi

# Link using gold.  This avoids running out of memory on 32-bit systems, and
# avoids a recurring build failure with GNU ld on other systems.
#mkdir -vpm755 $TMPBUILD/gold
#ln -vfs /usr/bin/ld.gold $TMPBUILD/gold/ld
#export PATH=$TMPBUILD/gold:$PATH
#export CC=${CC:-"gcc -B$TMPBUILD/gold/"}
#export CXX=${CXX:-"g++ -B$TMPBUILD/gold/"}

# Extract source:
echo "****** Extracting source... (will take a while) *******"
tar xf $CWD/$PKGNAM-${VERSION}.source.tar.?*
#tar xf $PORTCWD/sources/$PKGNAM-${VERSION}.source*tar*
cd comm*/ || cd $PKGNAM*/ || exit 1
slackhousekeeping

##############################################################################
# Apply patches for ARM:
##############################################################################

#for pf in \
#   \
#    seamonkey-2.53.10-allsettled.patch.xz \
#   \
#    ; do
#echo        auto_apply_patch $PORTCWD/sources/fedorapatches/${pf} || exit 1
#done

##############################################################################
# Apply patches from x86 Slackware:
##############################################################################
# Retain GTK+ v2 scrolling behavior:
zcat $CWD/sm.ui.scrollToClick.diff.gz | patch -p2 --verbose || exit 1

# Commented out since I take this from Fedora:
#

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

# Our building options, in a configure-like display ;)
# Slackware has: --enable-elf-hack but ARM always has this disabled.
# Not sure if it needs disabling, but this builds and runs so let's leave it.
# Also, not doing this since it complains:
#   --enable-rust \
# ERROR: Don't know how to translate arm-slackware-linux-gnueabihf for rustc
# I'm not too concerned about this but if anyone knows how to fix it, let me know.

# Set linker to use:
LINKER=bfd

OPTIONS="$SLKCONFARGS \
  --prefix=/usr \
  --libdir=/usr/lib${LIBDIRSUFFIX} \
  --enable-cpp-rtti \
  --enable-default-toolkit=cairo-gtk3 \
  --enable-startup-notification \
  --enable-alsa \
  --disable-debug \
  --enable-linker=$LINKER \
  --disable-strip \
  --disable-install-strip \
  --disable-tests \
  --disable-crashreporter \
  --disable-rust-simd \
  --enable-accessibility \
  $GOOGLE_API_KEY \
  --disable-updater \
  --enable-chrome-format=omni \
  --disable-necko-wifi \
  --enable-extensions=default \
  --enable-js-shell \
  $ELFHACK \
  --enable-release \
  --enable-calendar \
  --with-system-nss \
  --with-system-nspr \
  --with-system-zlib \
  --with-unsigned-addon-scopes=app,system \
  --enable-application=comm/suite \
  --target=${SLK_ARCH_HOST} \
  --host=${SLK_ARCH_HOST}"

# Tune down the numjobs to avoid build system overload:
export NUMJOBS="-j$(( $(nproc) -1 ))"

export BUILD_OFFICIAL=1
export MOZILLA_OFFICIAL=1
export MOZ_MAKE_FLAGS="$NUMJOBS"
export MOZ_LINK_FLAGS="$SLKLDFLAGS"
export LDFLAGS="$SLKLDFLAGS"
export MOZ_OPT_FLAGS="$SLKCFLAGS"
export CFLAGS="$SLKCFLAGS"
export CXXFLAGS="$SLKCXXFLAGS"
export DEBUGOPTS="--disable-debug --enable-strip"


# Disable debuginfo being compiled in. Helps reduce RAM use at build time.
export MOZ_DEBUG_FLAGS="-g0"

#ac_cv_path_MAKE=/usr/bin/make-3.80 \

# Clear some variables that could break the build
unset DBUS_SESSION_BUS_ADDRESS ORBIT_SOCKETDIR SESSION_MANAGER \
  XDG_SESSION_COOKIE XAUTHORITY MAKEFLAGS

# Assemble our .mozconfig:
echo > .mozconfig

# we don't on ARM since I already edited $PATH to find gold
## Tell .mozconfig about the selected compiler:
echo "export CC=\"${CC}\"" >> .mozconfig
echo "export CXX=\"${CXX}\"" >> .mozconfig

# Mozilla devs enforce using an objdir for building
# https://developer.mozilla.org/en/Configuring_Build_Options#Building_with_an_objdir
mkdir obj
echo "mk_add_options MOZ_OBJDIR=$(pwd)/obj" >> .mozconfig
# This directory is also needed or the build will fail:
mkdir -p obj

# Set options for $OPTIMIZE_FLAG:
echo "ac_add_options --enable-optimize=\"${OPTIMIZE_FLAG}\"" >> .mozconfig

# Write in it the options above
for option in $OPTIONS; do echo "ac_add_options $option" >> .mozconfig; done
echo "ac_add_options --disable-tests" >> .mozconfig

# Build:
./mach build -v || failmake

# Install into package:
DESTDIR=$PKG ./mach install || failinstall

# This remains the standard plugin directory for all browsers.
mkdir -p $PKG/usr/lib${LIBDIRSUFFIX}/mozilla/plugins

# This is traditional.
cd $PKG/usr/lib${LIBDIRSUFFIX}
if [ ! -e seamonkey ]; then
   ln -vsf seamonkey-${VERSION} seamonkey
fi

mkdir -p $PKG/usr/share/applications
cp -a $CWD/*.desktop $PKG/usr/share/applications
chown -R root:root $PKG/usr/share/applications
chmod 644 $PKG/usr/share/applications/*
mkdir -p $PKG/usr/share/pixmaps
cp -a $CWD/*.png $PKG/usr/share/pixmaps
chown -R root:root $PKG/usr/share/pixmaps
chmod 644 $PKG/usr/share/pixmaps/*

# Copy docs:
mkdir -p $PKG/usr/doc/$PKGNAM-$VERSION
cd mozilla
cp -fav \
    AUTHORS LEGAL LICENSE README.txt \
    $PKG/usr/doc/$PKGNAM-$VERSION

# Fix duplicate binary, https://bugzilla.mozilla.org/show_bug.cgi?id=658850
cd $PKG/usr/lib$LIBDIRSUFFIX/$PKGNAM
if cmp seamonkey seamonkey-bin ; then
  ln -vfs seamonkey-bin seamonkey
fi

# Add post-install script:
mkdir -p $PKG/install
install -vpm644 $CWD/slack-desc $PKG/install/
zcat $CWD/doinst.sh.gz | sed -e "s#usr/lib#usr/lib${LIBDIRSUFFIX}#g" > $PKG/install/doinst.sh

# Apply generic Slackware packaging policies:
cd $PKG
slackstripall   # strip all .a archives and all ELFs
slack_delete_lafiles # delete usr/lib{,64}/*.la
#slackstriprpaths     # strip rpaths
slackgzpages -i # compress man & info pages and delete usr/info/dir

# Change the architecture of the package name since Seamonkey 2.1b2+:
# doesn't support armv4:
# export SLACKPACKAGE=$PKGNAM-$VERSION-armv5t-$BUILD.tgz

slackslack      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
# Taken care of above:
#slackdesc       # install slack-desc and doinst.sh
slackmp         # run makepkg -l y -c n
