# Maintainer (Parabola): André Silva <emulatorman@parabola.nu>
# Contributor (Parabola): Márcio Silva <coadde@parabola.nu>
# Contributor (ConnochaetOS): Henry Jensen <hjensen@connochaetos.org>
# Contributor (Parabola): Luke Shumaker <lukeshu@sbcglobal.net>
# Contributor (Parabola): fauno <fauno@kiwwwi.com.ar>
# Contributor (Parabola): vando <facundo@esdebian.org>
# Contributor (Arch): Jakub Schmidtke <sjakub@gmail.com>
# Contributor: Figue <ffigue at gmail>
# Thank you very much to the older contributors:
# Contributor: evr <evanroman at gmail>
# Contributor: Muhammad 'MJ' Jassim <UnbreakableMJ@gmail.com> 

_pgo=true

# We're getting this from Debian Sid
_debname=iceweasel
_debver=29.0.1
_debrel=deb1
_debrepo=http://ftp.debian.org/debian/pool/main/
debfile() { echo $@|sed -r 's@(.).*@\1/&/&@'; }

_pkgname=iceweasel
pkgname=iceweasel-libre
epoch=1
pkgver=$_debver.$_debrel
pkgrel=1

pkgdesc="A libre version of Debian Iceweasel, the standalone web browser based on Mozilla Firefox."
arch=(i686 x86_64 mips64el)
license=(MPL GPL LGPL)
depends=(alsa-lib dbus-glib desktop-file-utils gtk2 hicolor-icon-theme hunspell icu libevent libnotify libvpx libxt mime-types mozilla-common mozilla-searchplugins nss sqlite startup-notification)
makedepends=(autoconf2.13 diffutils gstreamer0.10-base imagemagick imake inetutils libidl2 libpulse librsvg libxslt mesa pkg-config python2 quilt unzip zip)
[ "$CARCH" != "mips64el" ] && makedepends+=('yasm')
options=(!emptydirs !makeflags)
if $_pgo; then
  makedepends+=(xorg-server-xvfb)
  options+=(!ccache)
fi
optdepends=('networkmanager: Location detection via available WiFi networks'
            'gstreamer0.10-base-plugins: vorbis decoding, ogg demuxing'
            'gstreamer0.10-good-plugins: webm and mp4 demuxing'
            'gstreamer0.10-bad-plugins: aac, vp8 and opus decoding'
            'gstreamer0.10-ugly-plugins: h.264 and mp3 decoding'
            'gstreamer0.10-ffmpeg: more decoders'
            'libpulse: PulseAudio audio driver')
url="http://packages.debian.org/sid/${_pkgname}"
install=iceweasel.install
replaces=('firefox')
conflicts=('firefox')
provides=('firefox')
source=("$_debrepo/`debfile $_debname`_$_debver.orig.tar.bz2"
        "$_debrepo/`debfile $_debname`_$_debver-${_debrel#deb}.debian.tar.xz"
        mozconfig
        mozconfig.pgo
        libre.patch
        gnu_headshadow.png
        iceweasel.desktop
        iceweasel-install-dir.patch
        vendor.js
        iceweasel-20.0.1-fixed-loading-icon.png
        Bug-756390-Make-the-Reset-Firefox-feature-more-gener.patch
        Fixup-Reset-Firefox-after-bad-merge.patch)
md5sums=('4db358c753cb15a526dfe79c6602c886'
         '134a1bfe72a940ec6673ee6883a03b68'
         '92a08a18995b915d6a6d0dab93ec6c1d'
         'df08eaa1ac3bc6c2356be4fbf8ec8932'
         '5d22063ebea2472dd0b1163b32b2050b'
         'b03a979a78484503ba8dddad4f2c96d1'
         '7b9e5996dd9fe0b186a43a297db1c6b5'
         '1c42509891cf6843660a5f3c69896e80'
         '783a5927246f014855b96a3abb92566b'
         '6e335a517c68488941340ee1c23f97b0'
         '9d1cc7b80085a4438305e9e37d42745b'
         '8e165ef85ddd72491f0b48f8954afca6')

prepare() {
  export DEBIAN_BUILD="mozilla-release"

  export QUILT_PATCHES=debian/patches
  export QUILT_REFRESH_ARGS='-p ab --no-timestamps --no-index'
  export QUILT_DIFF_ARGS='--no-timestamps'

  mv debian "$srcdir/$DEBIAN_BUILD"
  cd "$srcdir/$DEBIAN_BUILD"

  # Doesn't apply and seems unimportant
  rm -v debian/patches/l10n/Place-google-and-gmail-before-yandex.patch || true

  # Doesn't works in some parts due it has patches for others locales languages, source code hasn't it
  rm -v debian/patches/debian-hacks/Bug-756390-Make-the-Reset-Firefox-feature-more-gener.patch || true

  # It needs to be patched after Bug-756390-Make-the-Reset-Firefox-feature-more-gener.patch
  rm -v debian/patches/debian-hacks/Fixup-Reset-Firefox-after-bad-merge.patch || true

  quilt push -av

  install -m644 "$srcdir/gnu_headshadow.png" browser/base/content/abouthome # Put gnu_headshadow.png on the source code

  patch -Np1 -i "$srcdir/Bug-756390-Make-the-Reset-Firefox-feature-more-gener.patch" # Adding fixed Bug-756390-Make-the-Reset-Firefox-feature-more-gener.patch
  patch -Np1 -i "$srcdir/Fixup-Reset-Firefox-after-bad-merge.patch"
  patch -Np1 -i "$srcdir/iceweasel-install-dir.patch" # install to /usr/lib/$_pkgname

  # Patch and remove anything that's left
  patch -Np1 -i "$srcdir/libre.patch"
  sed -i 's|Adobe Flash|SWF Player|g;
         ' browser/base/content/pageinfo/permissions.js \
           browser/base/content/browser-plugins.js
  sed -i '\|["]displayName["][:] ["]Flash["]| s|Flash|SWF Player|
          \|["]displayName["][:] ["]Shockwave["]| s|Shockwave|DCR Player|
          \|["]displayName["][:] ["]QuickTime["]| s|QuickTime|MOV Player|
          \|installLinux| s|true|false|
         ' browser/base/content/browser-plugins.js
  sed -i '\|URL of the GeoLocation backend|d;
          \|geo[.]wifi[.]uri|d;
         ' browser/app/profile/firefox.js \
           browser/metro/profile/metro.js
  rm -v browser/base/content/abouthome/snippet*.png || true
  sed -i "\|abouthome/snippet|d" browser/base/jar.mn

  # Replace common URLs
  sed -i '\|extensions[.]getAddons[.]get[.]url| s|https://services[.]addons[.]mozilla[.]org.\+["][)][;]|https://trisquel.info/en/browser");|g;
          \|extensions[.]getAddons[.]search[.]browseURL| s|https://addons[.]mozilla[.]org.\+["][)][;]|https://trisquel.info/en/browser");|g;
          \|extensions[.]getAddons[.]search[.]url| s|https://services[.]addons[.]mozilla[.]org.\+["][)][;]|https://trisquel.info/en/browser");|g;
          \|extensions[.]webservice[.]discoverURL| s|https://services[.]addons[.]mozilla[.]org.\+["][)][;]|https://trisquel.info/en/browser");|g;
          \|browser[.]search[.]searchEnginesURL| s|https://addons[.]mozilla[.]org.\+["][)][;]|https://trisquel.info/en/browser");|g;
          \|plugins[.]update[.]url| s|https://www[.]mozilla[.]org/[%]LOCALE[%]/plugincheck/["][)][;]|https://trisquel.info/en/browser");|g;
         ' browser/app/profile/firefox.js

  cp "$srcdir/mozconfig" .mozconfig # Load our build config, disable SafeSearch

  if $_pgo; then
    cat "$srcdir/mozconfig.pgo" >> .mozconfig
  fi

  # From js on abslibre-mips64el.git
  if [ "$CARCH" = "mips64el" ]; then
      msg "Force disabling JIT."
      sed -ri 's/#define ENABLE_(JIT|ASSEMBLER) 1/#define ENABLE_\1 0/' \
          js/src/assembler/wtf/Platform.h
      sed -ri 's/ENABLE_(JIT|ASSEMBLER)=1/ENABLE_\1=0/' js/src/Makefile.{in,ref}

      echo "ac_add_options --disable-methodjit" >> .mozconfig
      echo "ac_add_options --disable-tracejit" >> .mozconfig
  fi

  # This is a bug, we should fix it
  if [ "$CARCH" = "mips64el" ]; then
      # Fix MIPS N32 support.
      sed -i 's/defined(_ABIO32)/(defined(_ABIO32) || defined(_ABIN32))/' \
          js/src/assembler/wtf/Platform.h
      # Disable JIT.
      sed -ri 's/#define ENABLE_(JIT|ASSEMBLER) 1/#define ENABLE_\1 0/' \
          js/src/assembler/wtf/Platform.h
      sed -ri 's/ENABLE_(JIT|ASSEMBLER)=1/ENABLE_\1=0/' js/src/Makefile.in
      echo 'ac_add_options --disable-methodjit' >> .mozconfig
      echo 'ac_add_options --disable-tracejit' >> .mozconfig
      echo 'ac_add_options --disable-jemalloc' >> .mozconfig
  fi

  mkdir "$srcdir/path"

  # WebRTC build tries to execute "python" and expects Python 2
  ln -s /usr/bin/python2 "$srcdir/path/python"

  # Use gold, as Mozilla can use some of its features, such as safe ICF
  #ln -s /usr/bin/ld.gold "$srcdir/path/ld"

  # configure script misdetects the preprocessor without an optimization level
  # https://bugs.archlinux.org/task/34644
  sed -i '/ac_cpp=/s/$CPPFLAGS/& -O2/' configure

  # Fix tab loading icon (flickers with libpng 1.6)
  # https://bugzilla.mozilla.org/show_bug.cgi?id=841734
  cp "$srcdir/iceweasel-20.0.1-fixed-loading-icon.png" \
    browser/themes/linux/tabbrowser/loading.png

  # Remove non-existent file on Makefile.in
  sed -i '\|build/pgo/blueprint/valid.png|d' build/Makefile.in
}

build() {
  export DEBIAN_BUILD="mozilla-release"

  cd "$srcdir/$DEBIAN_BUILD"

  export PATH="$srcdir/path:$PATH"
  export LDFLAGS="$LDFLAGS -Wl,-rpath,/usr/lib/$_pkgname"
  export PYTHON="/usr/bin/python2"

  if [[ $CARCH == i686 ]]; then
    # Work around memory address space exhaustion during linking on i686
    LDFLAGS+=' -Wl,--no-keep-memory'
  fi

  if $_pgo; then
    # Set up PGO
    export DISPLAY=:99
    Xvfb -nolisten tcp -extension GLX -screen 0 1280x1024x24 $DISPLAY &

    if ! make -f client.mk build MOZ_PGO=1; then
      kill $!
      return 1
    fi

    kill $! || true
  else
    make -f client.mk build
  fi
}

package() {
  export DEBIAN_BUILD="mozilla-release"

  cd "$srcdir/$DEBIAN_BUILD"
  make -f client.mk DESTDIR="$pkgdir" INSTALL_SDK= install

  install -Dm644 ../vendor.js "$pkgdir/usr/lib/$_pkgname/browser/defaults/preferences/vendor.js"

  # I don't even know why we're hitting the objdir, and ConnOS didn't
  _brandingdir=debian/branding
  brandingdir=moz-objdir/$_brandingdir
  icondir="$pkgdir/usr/share/icons/hicolor"
  for i in 16x16 32x32 48x48 64x64; do
    install -Dm644 "$brandingdir/default${i/x*/}.png" "$icondir/$i/apps/$_pkgname.png"
  done
  install -Dm644 "$brandingdir/mozicon128.png"      "$icondir/128x128/apps/$_pkgname.png"
  install -Dm644 "$_brandingdir/iceweasel_icon.svg" "$icondir/scalable/apps/$_pkgname.svg"

  install -d                                        "$pkgdir/usr/share/applications"
  install -m644  "$srcdir/iceweasel.desktop"        "$pkgdir/usr/share/applications"

  rm -rf "$pkgdir/usr/lib/$_pkgname/"{dictionaries,hyphenation}
  ln -sf /usr/share/hunspell            "$pkgdir/usr/lib/$_pkgname/dictionaries"
  ln -sf /usr/share/hyphen              "$pkgdir/usr/lib/$_pkgname/hyphenation"

  rm -rf "$pkgdir/usr/lib/$_pkgname/browser/"{searchplugins,plugins}
  ln -sf /usr/lib/mozilla/plugins       "$pkgdir/usr/lib/$_pkgname/browser/plugins"
  ln -sf /usr/lib/mozilla/searchplugins "$pkgdir/usr/lib/$_pkgname/browser/searchplugins"

  # Workaround for now: https://bugzilla.mozilla.org/show_bug.cgi?id=658850
  ln -sf $_pkgname "$pkgdir/usr/lib/$_pkgname/$_pkgname-bin"
}