# Maintainer: jc_gargma <jc_gargma@iserlohn-fortress.net>
# Maintainer (AUR): Figue <ffigue@gmail.com>
# Maintainer (AUR): Luna Jernberg <droidbittin@gmail.com>
# Contributor: Aqua-sama <aqua@iserlohn-fortress.net>
# Contributor (Arch: Jan Alexander Steffens (heftig) <heftig@archlinux.org>
# Contributor (Arch): Ionut Biru <ibiru@archlinux.org>
# Contributor (Arch): Jakub Schmidtke <sjakub@gmail.com>

# # I maintain this because:
# Arch version uses eme
# Arch version uses git
# Arch version uses python2
# Arch version uses clang
# Arch version requires signed addons
# Arch version doesn't remove system addons
# Arch version enables debug symbols
# Arch version lacks privacy and security by default
# Arch version uses alternate name which breaks addon packages

_modpgo=0

_pkgname=firefox
pkgname=${_pkgname}-esr
pkgver=91.7.0
_pkgver=${pkgver}esr
pkgrel=2
pkgdesc="Standalone web browser from mozilla.org"
arch=(x86_64 aarch64)
license=(MPL GPL LGPL)
url="https://www.mozilla.org/en-US/firefox/enterprise/"
depends=(gtk3 libxt mime-types dbus-glib ffmpeg4.4 ttf-font libpulse alsa-lib
         bzip2 libffi icu libjpeg-turbo libevent libvpx nspr nss pixman libpng sqlite libwebp zlib)
makedepends=(unzip zip diffutils yasm mesa imake inetutils xorg-server-xvfb
             autoconf2.13 rust clang llvm jack nodejs cbindgen nasm
             python-setuptools python-psutil python-zstandard lld dump_syms)
optdepends=('networkmanager: Location detection via available WiFi networks'
            'libnotify: Notification integration'
            'alsa-utils: ALSA support'
            'jack: Jack support'
            'pulseaudio: PulseAudio support'
            'speech-dispatcher: Text-to-Speech'
            'hunspell-en_CA: Spell checking, Canadian English'
            'xdg-desktop-portal: Screensharing with Wayland'
            'firefox-preferences: Custom vendor.js with security by default'
            'firefox-preferences-basic: Custom vendor.js with less breaking changes')
options=(!emptydirs !makeflags !lto !debug)
conflicts=(firefox)
provides=(firefox)
source=(
        "https://archive.mozilla.org/pub/$_pkgname/releases/$_pkgver/source/$_pkgname-$_pkgver.source.tar.xz"{,.asc}
        0001-Use-remoting-name-for-GDK-application-names.patch
        $pkgname.desktop
        identity-icons-brand.svg
        distribution.ini
        #mozconfig.in.gcc
        mozconfig.in.clang
        mozconfig.common.override
        #arc4_enable-lto-for-gcc.patch
        #firefox-gcc-build.patch
        #arc4_enable-pgo-for-gcc.patch
        #pgo.patch
        arc4_remove-health-reporting.patch
        arc4_remove-system-addons.patch
        )
sha256sums=('9c3ae9abe1ef10d66d64cbbee96ba2c16840098de8fe0285959f04160d0fee5a'
            'SKIP'
            '138b972a40a74104791783167770c4a01e62cce00bb9cc75119e152f9ea9f14d'
            'ac4b028a8b62f977e8210b4d44bfcb21a0ef97783ed338acc44ba29c27a9ef7a'
            'a9b8b4a0a1f4a7b4af77d5fc70c2686d624038909263c795ecc81e0aec7711e9'
            '0ba4d1a619a3a5750a5a48c6bff8c6a69d3aa4be4c303032c5979ab5f68db208'
            'd0e26768f7f9731bd04f5fa21662f95fa7137727c45561c33d82c418c5af11f2'
            '43905e3798f79b9b0306e3d702297c61fbeb7a0b577f5fcaa29734b29d11d0a1'
            'd2cd833695084ad6b9d51c669bb3bd0752519f5bc5dfb7e833bdc5eb1788b9e2'
            '4b53551d71962b02bd5226585a13f81fac322c690d5e3481ba18262cccc0d9c7')
b2sums=('374da61d89d4b7b24d01e8101926056d6819e7c34c80630694cd2d95193dd6662ccfe3195361e7cd5a4167098e74bb7018d02d5af715fdcf95228bf8f54cb1c2'
        'SKIP'
        'cfd09442eb344fb80b2233da86a101082926b9942849d988d0e43cac4cb6c15690dc8eae42514e114260b712c206cacd81f773e401cf8f861ee4b805fb872643'
        '6950ed417bfc38bec01e9b429e4a6d9a46267c27148a9def3477049723ad43658791fdcf4019e72ac3da1891fd800a72cf44be5911146dfd6a1f7a315dbe556e'
        '63a8dd9d8910f9efb353bed452d8b4b2a2da435857ccee083fc0c557f8c4c1339ca593b463db320f70387a1b63f1a79e709e9d12c69520993e26d85a3d742e34'
        '877eda442eb4730600dccf209a6e961ad3122ab456bbfda4ff041e8493ebaaf96224ac218360931259ff4214482f6bf65b3a3052f977ade1a274f38ffd859535'
        '645e9438585624c5ae20cd5fd8e59c912734ea6e5bbfb33ddeb226f3b88e1b443c334684b0445b748f6cbe64506acf8710f265b87efa6bfc2f0aa5623680aed0'
        '0f8e203bda791428acf526481959978d26e988d34b5f0490c2f9ac3307feefaf7ec7511ba4647c3f254c86288a7265476df860dee38ae5a7aaba9e264b1fe4bc'
        '1dce1277c0c8b83089551057ed61c8794aa65242d0c19573dab96081f00b1042af73fbc0a40ba49dfa31eff46f4636ffd985cf8e6bd28db614a639ca6c11c74e'
        '379adf3726664668f6167eaeab35dec40342d9288ff081d22a8363f163ab0945b17ce69e7d4276a31e99e56f690afa070c410c51a5060ed835356fd216256e7b')
validpgpkeys=('14F26682D0916CDD81E37B6D61B7B526D98F0353')  # Mozilla Software Releases

prepare() {
  mkdir mozbuild
  cd ${_pkgname}-${pkgver}

  # https://bugzilla.mozilla.org/show_bug.cgi?id=1530052
  patch -Np1 -i ../0001-Use-remoting-name-for-GDK-application-names.patch

  if [ "${_modpgo}" == "1" ]; then
    # Add the custom mozconfig for clang pgo
    cp $srcdir/mozconfig.in.clang $srcdir/${_pkgname}-${pkgver}/.mozconfig
  cat >$srcdir/${_pkgname}-${pkgver}/.mozconfig - <<END
mk_add_options MOZ_OBJDIR=${PWD@Q}/obj
ac_add_options --enable-profile-generate=cross
END
  elif [ "${_modpgo}" == "0" ]; then
    # Add the custom mozconfig for clang
    cp $srcdir/mozconfig.in.clang $srcdir/${_pkgname}-${pkgver}/.mozconfig
  cat >$srcdir/${_pkgname}-${pkgver}/.mozconfig - <<END
mk_add_options MOZ_OBJDIR=${PWD@Q}/obj
END
  fi

  # MOZ_TELEMETRY_REPORTING only applied correctly when set in this override file
  cp $srcdir/mozconfig.common.override $srcdir/${_pkgname}-${pkgver}/build/mozconfig.common.override


  # Disable various components at the source level
  sed -i 's|[;]1|;0|' $srcdir/${_pkgname}-${pkgver}/toolkit/components/telemetry/TelemetryStartup.manifest
  sed -i 's/;1/;0/' $srcdir/${_pkgname}-${pkgver}/toolkit/components/telemetry/components.conf

  # Patch out health reporting so that MOZ_DATA_REPORTING=0 can be applied.
  patch -Np1 -i ../arc4_remove-health-reporting.patch

  # Remove @RESPATH@/browser/features/* to prevent system addons from being part of the output package.
  patch -Np1 -i ../arc4_remove-system-addons.patch


  # Hide mobile promo
#  echo ".fxaMobilePromo {  display: none !important; }" >> browser/themes/shared/incontentprefs/preferences.inc.css
  # Hide plugindeprecation-notice
  echo "#plugindeprecation-notice {  display: none !important; }" >> toolkit/mozapps/extensions/content/extensions.css
  # Hide warnings on unsigned extensions
  echo ".warning{display: none!important; } .addon[notification=warning]{background-image: none!important;}" >> toolkit/mozapps/extensions/content/extensions.css
}

build() {
  cd ${_pkgname}-${pkgver}

  export MOZ_NOSPAM=1
  export MOZBUILD_STATE_PATH="$srcdir/mozbuild"
  export MACH_USE_SYSTEM_PYTHON=1

  # firefox is prone to OOM, use 1 thread per 2GB ram
  #export MOZ_MAKE_FLAGS="${MAKEFLAGS}"
  export MOZ_MAKE_FLAGS="-j32"

  # -flto breaks cargo
  # -fPIE and -pie break compiling
  export CFLAGS="$CFLAGS -O3 -fstack-protector-all -fPIC"
  export CXXFLAGS="$CXXFLAGS -O3 -fstack-protector-all -fPIC"

  # LTO needs more open files
  ulimit -n 4096


  if [ "${_modpgo}" == "1" ]; then
  # clang does not support -fstack-clash-protection, so remove it
  #export CFLAGS="$(echo $CFLAGS | sed 's/ -fstack-clash-protection//' - )"
  #export CXXFLAGS="$(echo $CXXFLAGS | sed 's/ -fstack-clash-protection//' - )"

  # Do 3-tier PGO
  echo "Building instrumented browser..."
  ./mach build

  echo "Profiling instrumented browser..."
  ./mach package
  LLVM_PROFDATA=llvm-profdata \
    JARLOG_FILE="$PWD/jarlog" \
    xvfb-run -s "-screen 0 1920x1080x24 -nolisten local" \
    ./mach python build/pgo/profileserver.py

  stat -c "Profile data found (%s bytes)" merged.profdata
  test -s merged.profdata

  stat -c "Jar log found (%s bytes)" jarlog
  test -s jarlog

  echo "Removing instrumented browser..."
  ./mach clobber

  echo "Building optimized browser..."
  # Add the custom mozconfig
  cp $srcdir/mozconfig.in.clang $srcdir/${_pkgname}-${pkgver}/.mozconfig
  cat >$srcdir/${_pkgname}-${pkgver}/.mozconfig - <<END
mk_add_options MOZ_OBJDIR=${PWD@Q}/obj
ac_add_options --enable-lto=cross
ac_add_options --enable-profile-use=cross
ac_add_options --with-pgo-profile-path=${PWD@Q}/merged.profdata
ac_add_options --with-pgo-jarlog=${PWD@Q}/jarlog
END
  ./mach build

  else
    echo "Building optimized browser..."
    xvfb-run -s "-screen 0 1920x1080x24 -nolisten local" ./mach build
  fi
}

package() {
  cd ${_pkgname}-${pkgver}
  DESTDIR="$pkgdir" ./mach install

  # Don't install in /usr/local
  rm -rf "$pkgdir/usr/local/bin"
  mkdir "$pkgdir/usr/lib"
  mkdir "$pkgdir/usr/bin"
  cp -r --reflink "$pkgdir/usr/local/lib/firefox" "$pkgdir/usr/lib/firefox"
  rm -rf "$pkgdir/usr/local/lib/firefox"

  install -Dm644 $srcdir/distribution.ini \
  "$pkgdir/usr/lib/$_pkgname/distribution/distribution.ini"

  # use a symlink in /usr/bin instead
  ln -sf "/usr/lib/$_pkgname/firefox" "$pkgdir/usr/bin/firefox"


  # icons
  local i theme=official
  for i in 16 22 24 32 48 64 128 256; do
    install -Dvm644 browser/branding/$theme/default$i.png \
      "$pkgdir/usr/share/icons/hicolor/${i}x${i}/apps/$pkgname.png"
  done
  install -Dvm644 browser/branding/$theme/content/about-logo.png \
    "$pkgdir/usr/share/icons/hicolor/192x192/apps/$pkgname.png"
  install -Dvm644 browser/branding/$theme/content/about-logo@2x.png \
    "$pkgdir/usr/share/icons/hicolor/384x384/apps/$pkgname.png"
  install -Dvm644 browser/branding/$theme/content/about-logo.svg \
    "$pkgdir/usr/share/icons/hicolor/scalable/apps/$pkgname.svg"
  install -Dvm644 ../identity-icons-brand.svg \
    "$pkgdir/usr/share/icons/hicolor/symbolic/apps/$pkgname-symbolic.svg"

  # install desktop file
  install -Dvm644 ../$pkgname.desktop \
    "$pkgdir/usr/share/applications/$pkgname.desktop"

   # Use system certificates
  local nssckbi="$pkgdir/usr/lib/$_pkgname/libnssckbi.so"
  if [[ -e $nssckbi ]]; then
    ln -srfv "$pkgdir/usr/lib/libnssckbi.so" "$nssckbi"
  fi
}