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

# mozilla-thunderbird.SlackBuild
# by Stuart Winter <mozes@slackware.com>
# 26-Apr-2005
#
# Copyright 2008, 2009, 2010, 2011, 2012, 2014, 2016, 2017  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

RELEASEVER=$(echo $VERSION | cut -f 1 -d e | cut -f 1 -d b)
echo "Release version: $RELEASEVER"

# 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:
case $ARCH in
   arm)     export SLKCFLAGS="-O2 $SLKCFLAGS -std=gnu99 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -fpermissive -Wformat-security -Wformat -Werror=format-security -fno-delete-null-pointer-checks -fPIC -Wl,-z,relro -Wl,-z,now"
#            export SLKCXXFLAGS="-g -std=gnu++0x"
            export SLKCXXFLAGS="$SLKCFLAGS"
            export LDFLAGS="-Wl,--no-keep-memory -Wl,--reduce-memory-overheads"

            # The little hacks section:
            # Firefox 17.0 adds webrtc but it does not work on ARM
            SLKCONFARGS="--disable-webrtc"
            #
            # --with-system-libvpx=/tmp/pkg-libvpx
            export SLKCONFARGS="$SLKCONFARGS \
                                \
                                --with-float-abi=hard \
                                --with-arch=armv7-a \
                                --with-fpu=vfpv3-d16 \
                                \
                                --disable-crashreporter \
                                --disable-elf-hack \
                                --disable-ion \
                                --disable-jemalloc \
                                --disable-strip \
                                --disable-necko-wifi \
                                --disable-updater \
                                --disable-system-sqlite \
                                --without-system-jpeg \
                               \
                                --enable-system-ffi \
                                --enable-readline \
                                --enable-pie \
                                --with-pthreads \
                                --with-system-nss \
                                --with-system-icu \
                                --with-system-nspr \
                                --with-system-libvpx \
                                --with-system-libevent \
                                --enable-extensions=default \
                                \
                                --host=arm-linux-gnueabihf \
                                --target=arm-linux-gnueabihf"
            export LIBDIRSUFFIX="" ;;
   *)       export SLKCFLAGS="-O" ;;
             # For aarch64, add --disable-ion
esac

# Put Rust objects on a diet to keep the linker from running into memory
# issues (especially on 32-bit):
export RUSTFLAGS="-Cdebuginfo=0"

# 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-api-keyfile=$PORTCWD/.GoogleSafeBrowsingAPI_Key"
fi

# Figure out if this is a beta, or a release:
MOZLOCALIZE=${MOZLOCALIZE:-}

# Extract source:
echo "[**] Extracting source [**]"
tar xf $CWD/thunderbird-*source.tar.!(*sign|*asc|*sig)
#tar xf $PORTCWD/sources/thunderbird-*source.tar.!(*sign|*asc|*sig)
cd thunderbird* || exit 1
slackhousekeeping

# Taken from Fedora's spec file###
# Update the various config.guess to upstream release for aarch64 support
find ./ -name config.guess -exec cp /usr/share/automake-*/config.guess {} ';'
######

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

# Fix build when using Rust 1.29.0:
# This is replicated below by 'build-triplet-failure.patch'
#zcat $CWD/mozilla.rust_1_29_0.patch.gz | patch -p1 --verbose || exit 1

#
# Apply some patches from Fedora:
ln -vfs comm mozilla-release # just a hack to avoid editing the patches
ln -vfs comm mozilla # just a hack to avoid editing the patches
# Patch list taken from Fedora's build log:
# wget -O- https://kojipkgs.fedoraproject.org/packages/thunderbird/60.2.1/2.fc30/data/logs/armv7hl/build.log|grep "^Patch "|awk -F'(' '{print $2}'|sed -e 's?):$??g' -e 's?$? \\?g' -e 's?^?    ?g'
#
for pf in \
    \
    mozilla-build-arm.patch \
    firefox-gcc-6.0.patch \
    mozilla-1245783.patch \
    build-triplet-failure.patch \
    mozilla-1460871-ldap-query.patch \
    build-jit-atomic-always-lucky.patch \
    build-aarch64-skia.patch \
    Bug-1238661---fix-mozillaSignalTrampoline-to-work-.patch \
    bug1375074-save-restore-x28.patch \
    mozilla-1353817.patch \
    build-disable-elfhack.patch \
   \
 ; do
    # Some patches only apply when pwd is "mozilla", so re-try once:
     auto_apply_patch $PORTCWD/sources/fedorapatches/$pf || ( cd mozilla ; auto_apply_patch $PORTCWD/sources/fedorapatches/$pf || exit 1 ) || exit 1
done

# Use the 'gold' ld linker due to RAM issues:
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"}

# This can be set to YES or NO:
ENABLE_CALENDAR=${ENABLE_CALENDAR:-YES}
if [ "$ENABLE_CALENDAR" = "NO" ]; then
  ENABLE_CALENDAR="--disable-calendar"
else
  ENABLE_CALENDAR="--enable-calendar"
fi

# Configure options:
OPTIONS=" $SLKCONFARGS \
   --enable-official-branding \
   --prefix=/usr \
   --libdir=/usr/lib${LIBDIRSUFFIX} \
   --with-system-zlib \
   --enable-alsa \
   --enable-application=comm/mail \
   $ENABLE_CALENDAR \
   --enable-default-toolkit=cairo-gtk3 \
   --enable-startup-notification \
   --enable-ldap \
   --enable-cpp-rtti \
   --enable-accessibility \
   $GOOGLE_API_KEY \
   --disable-debug \
   --disable-tests"

# Test:
#   --enable-strip \

if [ ! -z $MOZLOCALIZE ]; then
  OPTIONS=$OPTIONS" \
  --enable-ui-locale=$MOZLOCALIZE
  --with-l10n-base=.."
  # There are no dictionaries in localized builds
  sed -i \
    -e "/@BINPATH@\/dictionaries\/\*/d" \
    -e "/@RESPATH@\/dictionaries\/\*/d" \
    mail/installer/package-manifest.in || exit 1
fi

# Broken with thunderbird 12.0:
#  --enable-system-cairo \

# ARM: Reduce parallel build jobs to 3 otherwise the build host gets hammered:
if [ ! -z "$NUMJOBS" ]; then
   export NUMJOBS="-j3"
 else
   # Not running parallel, so we'll use 1 core.
   export NUMJOBS="-j1"
fi

# Build thunderbird:
echo "[**] Building thunderbird [**]"
#find . -name configure.in | while read line ; do touch ${line%.*}; done
#find . -name configure.in | while read line ; do touch ${line%%configure.in}/config.status; done
export BUILD_OFFICIAL=1
export MOZILLA_OFFICIAL=1
export MOZ_PHOENIX=1
export MOZ_MAKE_FLAGS="$NUMJOBS"
export CFLAGS="$SLKCFLAGS"
export CXXFLAGS="$SLKCFLAGS"

# 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

# 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 mozilla/obj

# Write in it the options above
for option in $OPTIONS; do echo "ac_add_options $option" >> .mozconfig; done
# Work around the issue of spacing in the provided options, and add this directly:
echo 'ac_add_options --enable-optimize="-O2 -g -fno-schedule-insns"' >> .mozconfig

# Build:
#

####################################
# Taken from Fedora's spec file:
#echo "Generate big endian version of config/external/icu/data/icud58l.dat"
#./mach python intl/icu_sources_data.py .
#ls -la config/external/icu/data
#rm -fv config/external/icu/data/icudt*l.dat
####################################

# Work-around:
sed -i 's?-Werror??g' configure

# Build:
./mach -v configure
./mach build || exit 1
./mach buildsymbols || exit 1

# Install in to package:
DESTDIR=$PKG ./mach install || exit 1

# We don't need these (just symlinks anyway):
rm -rf $PKG/usr/lib${LIBDIRSUFFIX}/thunderbird-devel-$RELEASEVER

# Nor these:
rm -rf $PKG/usr/include

#  Thunderbird 3.x cruft?
#( cd $PKG/usr/lib${LIBDIRSUFFIX}/thunderbird-$VERSION
#  cp -a defaults/profile/mimeTypes.rdf defaults/profile/mimeTypes.rdf.orig
#  zcat $CWD/mimeTypes.rdf > defaults/profile/mimeTypes.rdf || exit 1
#) || exit 1

mkdir -p $PKG/usr/lib${LIBDIRSUFFIX}/mozilla/plugins
mkdir -p $PKG/usr/share/applications
cat $CWD/mozilla-thunderbird.desktop > $PKG/usr/share/applications/mozilla-thunderbird.desktop
mkdir -p $PKG/usr/share/pixmaps

# These files/directories are usually created if Thunderbird is run as root,
# which on many systems might (and possibly should) be never.  Therefore, if we
# don't see them we'll put stubs in place to prevent startup errors.
( cd $PKG/usr/lib${LIBDIRSUFFIX}/thunderbird-$RELEASEVER
  if [ -d extensions/talkback\@mozilla.org ]; then
    if [ ! -r extensions/talkback\@mozilla.org/chrome.manifest ]; then
      echo > extensions/talkback\@mozilla.org/chrome.manifest
    fi
  fi
  if [ ! -d updates ]; then
    mkdir -p updates/0
  fi
)

# Need some default icons in the right place:
for i in 16 22 24 32 48 256; do
  install -m 0644 -D comm/mail/branding/thunderbird/default${i}.png \
           $PKG/usr/share/icons/hicolor/${i}x${i}/apps/thunderbird.png
done
mkdir -p $PKG/usr/share/pixmaps
( cd $PKG/usr/share/pixmaps ; ln -sf /usr/share/icons/hicolor/256x256/apps/thunderbird.png . )
mkdir -p $PKG/usr/lib$LIBDIRSUFFIX/thunderbird-$RELEASEVER/chrome/icons/default
install -m 644 other-licenses/branding/thunderbird/mailicon16.png \
  $PKG/usr/lib$LIBDIRSUFFIX/thunderbird-$RELEASEVER/icons/
install -m 644 other-licenses/branding/thunderbird/mailicon16.png \
  $PKG/usr/lib$LIBDIRSUFFIX/thunderbird-$RELEASEVER/chrome/icons/default/

# Copy over the LICENSE
install -p -c -m 644 LICENSE $PKG/usr/lib${LIBDIRSUFFIX}/thunderbird-$RELEASEVER/

# 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      # chown -R root:root, chmod -R og-w, slackchown, slack644docs
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

# Clean up the residue for this hack:
rm -rf /tmp/pkg-libvpx
