# Maintainer (arch:thunderbird): Levente Polyak <anthraxx[at]archlinux[dot]org>
# Contributor: Jan Alexander Steffens (heftig) <jan.steffens@gmail.com>
# Contributor: Ionut Biru <ibiru@archlinux.org>
# Contributor: Alexander Baldeck <alexander@archlinux.org>
# Contributor: Dale Blount <dale@archlinux.org>
# Contributor: Anders Bostrom <anders.bostrom@home.se>
# Maintainer: Andreas Grapentin <andreas@grapentin.org>
# Contributor: André Silva <emulatorman@hyperbola.info>
# Contributor: Márcio Silva <coadde@hyperbola.info>
# Contributor: Luke R. <g4jc@openmailbox.org>
# Contributor: Isaac David <isacdaavid@isacdaavid.info>
# Contributor: bill-auger <bill-auger@programmer.net>


# parabola changes and rationale:
# libre:
#  - rebranded to icedove
# technical:
#  - added makedepends for branding: quilt, imagemagick
#  - use system python packages
# privacy:
#  - disabled geo-location


_pkgname=thunderbird
pkgname=icedove
epoch=1
pkgver=102.9.1
pkgrel=1
pkgrel+=.parabola1
_brandingver=102
_brandingrel=1
pkgdesc='Standalone mail and news reader from mozilla.org'
url=https://wiki.parabola.nu/${pkgname}
arch=(x86_64)
arch+=(i686 armv7h)
license=(MPL GPL LGPL)
depends=(
  glibc gtk3 libgdk-3.so libgtk-3.so mime-types dbus libdbus-1.so dbus-glib
  alsa-lib nss hunspell sqlite ttf-font libvpx libvpx.so zlib bzip2 libbz2.so
  botan libwebp libwebp.so libwebpdemux.so libevent libjpeg-turbo libffi
  libffi.so nspr gcc-libs libx11 libxrender libxfixes libxext libxcomposite
  libxdamage pango libpango-1.0.so cairo gdk-pixbuf2 icu libicui18n.so
  libicuuc.so freetype2 libfreetype.so fontconfig libfontconfig.so glib2
  libglib-2.0.so pixman libpixman-1.so gnupg json-c
)
makedepends=(
  unzip zip diffutils python nasm mesa libpulse libice libsm
  rust clang llvm cbindgen nodejs lld
  gawk perl findutils libotr wasi-compiler-rt wasi-libc wasi-libc++ wasi-libc++abi
)
makedepends+=(quilt imagemagick)
replaces=(${_pkgname})
options=(!emptydirs !makeflags !lto)
source=(https://archive.mozilla.org/pub/thunderbird/releases/$pkgver/source/thunderbird-$pkgver.source.tar.xz{,.asc}
        $pkgname.desktop
        vendor-prefs.js
        distribution.ini
        mozconfig.cfg
        metainfo.patch
        rustc_version-0.4.0.patch)
source=( ${source[*]/metainfo.patch/} ) # branding
source+=(https://repo.parabola.nu/other/icedove/${pkgname}_$_brandingver-$_brandingrel.branding.tar.xz{,.sig})
validpgpkeys=(
  14F26682D0916CDD81E37B6D61B7B526D98F0353 # Mozilla Software Releases <release@mozilla.com>
  4360FE2109C49763186F8E21EBE41E90F6F12F6D # Mozilla Software Releases <release@mozilla.com>
)
validpgpkeys+=(BFA8008A8265677063B11BF47171986E4B745536  # Andreas Grapentin
               3954A7AB837D0EA9CFA9798925DB7D9B5A8D4B40) # bill-auger


## dependency tweaks ##

case "${CARCH}" in
armv7h)
  makedepends=( ${makedepends[*]/wasi-*/} ) # armv7h has no wasi compiler
  ;;
i686)
  # currently fails to build for i686
  # -> rustup: error while loading shared libraries: libLLVM-14.so: cannot open shared object file: No such file or directory
  ;;
esac


prepare() {
  cd $_pkgname-$pkgver

  echo "${noextract[@]}"


  ## technical patching ##

  local src
  for src in "${source[@]}"; do
    src="${src%%::*}"
    src="${src##*/}"
    [[ $src = *.patch ]] || continue
    [[ $src = arm-wasm-vfp.patch ]] && continue # defer parabola patches

    echo "Applying patch $src..."
    patch -Np1 < "../$src"
  done


  ## general configuration ##

  cp ../mozconfig.cfg .mozconfig
  sed "s|@PWD@|${PWD@Q}|g" -i .mozconfig


  ## [ARCH-SPECIFIC CONFIG] ##

  case ${CARCH} in
  aarch64|armv7h)
    if [[ $CARCH == "armv7h" ]]; then
      echo "ac_add_options --disable-elf-hack" >> .mozconfig
      MAKEFLAGS="-j4"
      # disable hard-coded LTO
      sed -i '/cargo_rustc_flags += -Clto/d' config/makefiles/rust.mk
      sed -i '/RUSTFLAGS += -Cembed-bitcode=yes/d' config/makefiles/rust.mk
      # increase codegen-units due to RAM constraints
      sed -i 's/codegen-units=1/codegen-units=16/' config/makefiles/rust.mk
    fi
    echo 'ac_add_options --enable-optimize="-g0 -O2"' >> .mozconfig
    echo "mk_add_options MOZ_MAKE_FLAGS=\"${MAKEFLAGS}\"" >> .mozconfig

    export MOZ_DEBUG_FLAGS=" "
    export CFLAGS+=" -g0"
    export CXXFLAGS+=" -g0"
    #export LDFLAGS+=" -Wl,--no-keep-memory -Wl,--reduce-memory-overheads"
    export LDFLAGS+=" -Wl,--no-keep-memory"
    export RUSTFLAGS="-Cdebuginfo=0"
    CFLAGS=${CFLAGS/-fstack-clash-protection}
    CXXFLAGS=${CXXFLAGS/-fstack-clash-protection}

    # archarm has these in mozconfig.cfg
    sed -i 's|with-wasi-sysroot.*|without-wasm-sandboxed-libraries|' .mozconfig
    echo "ac_add_options --disable-webrtc"                        >> .mozconfig
    ;;
  i686)
    sed -i 's/--enable-linker=gold/--enable-linker=bfd/' .mozconfig
    LDFLAGS+=" -Wl,--no-keep-memory -Wl,--reduce-memory-overheads"
    export LDFLAGS
    ;;
  esac


  ## branding ##

  local branding_srcdir="${srcdir}"/${pkgname}-${_brandingver}
  local branding_destdir="${srcdir}"/${_pkgname}-${pkgver}/comm/mail/branding/${pkgname}
  local blank_svg='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"></svg>' # TODO: branding package

  # apply branding
  echo "applying parabola branding"
  export QUILT_PATCHES="${branding_srcdir}"/patches
  export QUILT_REFRESH_ARGS='-p ab --no-timestamps --no-index'
  export QUILT_DIFF_ARGS='--no-timestamps'
  export QUILT_PC="${srcdir}"/.pc
  rm -rf -- ${branding_destdir}
  cp -aT -- "${branding_srcdir}"/${pkgname}-branding ${branding_destdir}
  quilt push -av

  # customize distribution.ini
  local branding_gui_ver="(${_brandingver}-${_brandingrel} branding)"
  sed -i 's|archlinux|parabola|'                     "${srcdir}"/distribution.ini
  sed -i "s|version=.*|version=${branding_gui_ver}|" "${srcdir}"/distribution.ini
  sed -i 's|about=.*|about=Parabola Icedove|'        "${srcdir}"/distribution.ini
  sed -i 's|thunderbird|icedove|'                    "${srcdir}"/distribution.ini

  # customize .mozconfig
  sed -i 's|enable-official-branding|disable-official-branding|' .mozconfig
  sed -i 's|=org\.archlinux|=nu.parabola|'                       .mozconfig
  sed -i '/api-keyfile=/d'                                       .mozconfig
  cat >> .mozconfig <<EOF
ac_add_options --with-branding=${branding_destdir}
ac_add_options --disable-crashreporter
ac_add_options --disable-updater
EOF

  # stage "appdata" file
  cp "${branding_srcdir}"/${pkgname}.appdata.xml ${branding_destdir}/

  # generate icons, logos, banners
  for i in 16 22 24 32; do
    rsvg-convert -w ${i} -h ${i} "${branding_srcdir}"/app-icons/${pkgname}_small.svg \
      -o "${branding_destdir}/default${i}.png"
  done
  for i in 48 64 128 256; do
    rsvg-convert -w ${i} -h ${i} "${branding_srcdir}"/app-icons/${pkgname}_big.svg \
      -o "${branding_destdir}/default${i}.png"
  done
  echo "${blank_svg}" > ${branding_destdir}/${pkgname}-symbolic.svg # TODO: branding package
  cp "${branding_srcdir}"/preview.png comm/mail/themes/linux/mail/preview.png


  ## search-engines ##

  pushd comm/mail/components/search/extensions > /dev/null

  # Patch search-engines config
  sed -i 's|https://duckduckgo.com/|https://html.duckduckgo.com/html/|' ddg/manifest.json

  # Delete unused search engine configs
  find -mindepth 1 -maxdepth 1 \
       -not -name ddg          \
       -not -name wikipedia    \
       -exec rm -frv {} \;

  popd > /dev/null


  ## libre patching ##

  sed -i '\|Phishing Protection|d
          \|UrlClassifier|d
          \|URLClassifier|d
          \|url-classifier|d
         ' comm/mail/installer/package-manifest.in
}

build() {
  cd $_pkgname-$pkgver

  if [[ -n "${SOURCE_DATE_EPOCH}" ]]; then
    export MOZ_BUILD_DATE=$(date --date "@${SOURCE_DATE_EPOCH}" "+%Y%m%d%H%M%S")
  fi
  export MACH_BUILD_PYTHON_NATIVE_PACKAGE_SOURCE=system # parabola policy
  export MOZBUILD_STATE_PATH="${srcdir}/mozbuild"
  ./mach configure
  ./mach build
  ./mach buildsymbols
}

package() {
  optdepends=(
    'libotr: OTR support for active one-to-one chats'
    'libnotify: Notification integration'
  )

  cd $_pkgname-$pkgver
  DESTDIR="$pkgdir" ./mach install

  install -Dm 644 ../vendor-prefs.js -t "$pkgdir/usr/lib/$pkgname/defaults/pref"
  install -Dm 644 ../distribution.ini -t "$pkgdir/usr/lib/$pkgname/distribution"
  install -Dm 644 ../$pkgname.desktop -t "$pkgdir/usr/share/applications"
  install -Dm 644 comm/mail/branding/${pkgname}/${pkgname}.appdata.xml \
    "${pkgdir}/usr/share/metainfo/${pkgname}.appdata.xml"

  # NOTE: comm/mail/branding/${pkgname} is $branding_destdir in prepare()
  for i in 16 22 24 32 48 64 128 256; do
    install -Dm644 comm/mail/branding/${pkgname}/default${i}.png \
      "$pkgdir/usr/share/icons/hicolor/${i}x${i}/apps/$pkgname.png"
  done
  install -Dm644 comm/mail/branding/${pkgname}/${pkgname}-symbolic.svg \
    "$pkgdir/usr/share/icons/hicolor/symbolic/apps/$pkgname-symbolic.svg"

  # Use system-provided dictionaries
  ln -Ts /usr/share/hunspell "$pkgdir/usr/lib/$pkgname/dictionaries"
  ln -Ts /usr/share/hyphen "$pkgdir/usr/lib/$pkgname/hyphenation"

  # Install a wrapper to avoid confusion about binary path
  install -Dm755 /dev/stdin "$pkgdir/usr/bin/$pkgname" <<END
#!/bin/sh
exec /usr/lib/$pkgname/$pkgname "\$@"
END

  # Replace duplicate binary with wrapper
  # https://bugzilla.mozilla.org/show_bug.cgi?id=658850
  ln -srf "$pkgdir/usr/bin/$pkgname" \
    "$pkgdir/usr/lib/$pkgname/$pkgname-bin"
}

# checksums are here to reduce the diff against arch (arch bundles the lang-packs split-packages into this one)
sha512sums=('0a4aa344387d19ab6e8e70a08f27ea0e47e74f90e8cf47545870b7ef30b08babfae9be229b13bee31b6797c45683859ba54ecbc0d1e31c40f780851ae0c0a84b'
            'SKIP'
            'a3c9815491d9bed0440c60f35867a5b8a2a1343521f288035fcc46e651a11b926c75a9eca2d262b43d510a7a7119709b53637f1b00ddbbee8e5b0a4b33d7b8fd'
            '6918c0de63deeddc6f53b9ba331390556c12e0d649cf54587dfaabb98b32d6a597b63cf02809c7c58b15501720455a724d527375a8fb9d757ccca57460320734'
            '5cd3ac4c94ef6dcce72fba02bc18b771a2f67906ff795e0e3d71ce7db6d8a41165bd5443908470915bdbdb98dddd9cf3f837c4ba3a36413f55ec570e6efdbb9f'
            'a34dd97954f415a5ffe956ca1f10718bd164950566ceba328805c2ccbb54ed9081df07f2e063479bf932c4a443bb5b7443cca2f82eea3914465ed6e4863e0c0e'
            # metainfo.patch (over-ridden by branding package)
            '36d9662fc94cbf7dcf371adc13a9cda679bc75df961d86de019d3c8ebb0be3062d5ef762d175fab58696db74758100a65de45d7832e0e2bd4e15c901f72d8349'
)
sha512sums+=('c424e546b007bfd944f2cefcc73a5a98212a44e7ad54904a7d05dbc494664583af6d50eae8228101671575f3a5df1e79be31fabe1c26c3eec07cef90583691d0'
             'SKIP')
