# Copyright 2009, 2010 Elias Pipping <pipping@exherbo.org>
# Copyright 2009 Heiko Przybyl <zuxez@cs.tu-berlin.de>
# Distributed under the terms of the GNU General Public License v2

# You'll find new releases here:
# - http://omahaproxy.appspot.com/viewer
# - http://googlechromereleases.blogspot.com

CHROMIUM_CHANNEL=stable

MY_PN=chromium
MY_PNV=${MY_PN}-${PV}

require freedesktop-desktop gtk-icon-cache python [ has_lib=false ] toolchain-funcs

export_exlib_phases pkg_setup src_prepare src_configure src_compile src_test src_install pkg_postinst pkg_postrm

SUMMARY="The open-source project behind Google Chrome"
DESCRIPTION="Browser based on Blink and Google's V8 JavaScript engine."
HOMEPAGE="https://www.chromium.org/Home"
DOWNLOADS="
    https://storage.googleapis.com/chromium-browser-official/${MY_PNV}.tar.xz
    https://gsdview.appspot.com/chromium-browser-official/${MY_PNV}.tar.xz
"

LICENCES="
    BSD-3         [[ note = [ chromium itself ] ]]
    Apache-2.0    [[ note = [ skia ] ]]
    BSD-2         [[ note = [ bsdiff, bspatch ] ]]
    BSD-3         [[ note = [ dtoa, jscre, modp_b64, v8, webkit ] ]]
    GPL-2         [[ note = [ hunspell, 'Mozilla interface to Java Plugin APIs', npapi, nspr, nss ] ]]
    LGPL-2        [[ note = [ webkit ] ]]
    LGPL-2.1      [[ note = [ ffmpeg, hunspell, 'Mozilla interface to Java Plugin APIs', npapi, nspr,
                              nss, webkit ] ]]
    MPL-1.1       [[ note = [ hunspell, 'Mozilla interface to Java Plugin APIs', npapi, nspr, nss ] ]]
    MIT           [[ note = [ harfbuzz ] ]]
    public-domain [[ note = [ lzma_sdk, sqlite ] ]]
    GPL-3         [[ note = [ inox patchset ] ]]
"
SLOT="0"
MYOPTIONS="
    bindist
    cups
    gconf
    keyring [[ description = [ Store passwords using GNOME Keyring ] ]]
    pulseaudio
    platform:
        amd64
        x86
    x86_cpu_features:
        sse2
    ( providers: jpeg-turbo )
    ( providers: eudev systemd ) [[ number-selected = exactly-one ]]
"

# http://crbug.com/62803 tracks the addition of a use_openssl option. Once that bug is closed,
# use_openssl=1 can be passed; dev-libs/{nss,nspr} will no longer be needed. Note that that flag
# currently does not use system openssl but a bundled version from third_party/openssl!
# There is use_system_ssl for that

# 46.0.2490.86 fails with the latest libvpx-1.5.0
# media-libs/libvpx[>=1.?.0]
DEPENDENCIES="
    build:
        dev-lang/python:*[>=2.5&<3]
        dev-lang/yasm
        dev-perl/Switch
        dev-util/gperf[>=3.0.4]
        media-libs/libexif
        sys-devel/bison
        sys-devel/ninja
    build+run:
        app-speech/speechd[>=0.8]
        dev-libs/atk
        dev-libs/dbus-glib:1[>=0.84]
        dev-libs/expat
        dev-libs/glib:2[>=2.26] [[ note = [ for gsettings ] ]]
        dev-libs/libevent[>=1.4.13]
        dev-libs/libxml2:2.0[>=2.6.32]
        dev-libs/libxslt[>=1.1.26]
        dev-libs/nspr[>=4.0]
        dev-libs/nss[>=3.12.3] [[ note = [ see base/nss_util.cc for the version requirement ] ]]
        fonts/corefonts
        media-libs/flac
        media-libs/fontconfig
        media-libs/freetype:2
        media-libs/libpng:=[>=1.2.37]
        media-libs/libwebp[>=0.4]
        media-libs/opus[>=1.1-r1]
        media-libs/speex
        net-libs/libsrtp
        sys-apps/dbus
        sys-apps/pciutils
        providers:eudev? ( sys-apps/eudev )
        providers:systemd? ( sys-apps/systemd )
        sys-libs/zlib[>=1.2.7-r1]
        sys-sound/alsa-lib
        virtual/usb:1
        x11-libs/cairo[X]
        x11-libs/gdk-pixbuf:2.0
        x11-libs/gtk+:2[>=2.16]
        x11-libs/harfbuzz
        x11-libs/libX11
        x11-libs/libXScrnSaver
        x11-libs/libXcomposite
        x11-libs/libXdamage
        x11-libs/libXext
        x11-libs/libXfixes
        x11-libs/libXi
        x11-libs/libXrandr
        x11-libs/libXrender
        x11-libs/libXtst
        x11-libs/pango
        cups? (
            dev-libs/libgcrypt
            net-print/cups
            x11-libs/gtk+:2[>=2.16][cups]
        )
        gconf? ( gnome-platform/GConf:2 )
        keyring? ( gnome-desktop/libgnome-keyring:1 )
        providers:jpeg-turbo? ( media-libs/libjpeg-turbo )
        pulseaudio? ( media-sound/pulseaudio )
    recommendation:
        fonts/corefonts [[ description = [ Needed to display some websites ] ]]
        x11-apps/xdg-utils [[ description = [ Set as default browser. Use application launchers for downloaded files (only for Gnome/KDE/Xfce) ] ]]
    suggestion:
        gnome-desktop/adwaita-icon-theme [[ description = [ For the downloads tab ] ]]
        net-www/google-talkplugin [[ description = [ Plugin necessary for google hangouts ] ]]
"

WORK=${WORKBASE}/${MY_PNV}

DEFAULT_SRC_COMPILE_PARAMS=( chrome chrome_sandbox )

cxx_is_gxx() {
    [[ ${CXX} == *g++* ]] && [[ ${CXX} != *clang* ]]
}

eninja() {
    edo ninja -j ${EXJOBS:-1} -v "$@"
}

inox_pkg_setup() {
    export BUILDTYPE=Release
    export V=1

    # For ffmpeg's linking
    export LD="${CXX}"

    exdirectory --allow /opt
}

inox_src_prepare() {
    default

    edo sed \
        -e '/-O>(debug_optimize)/d' \
        -e '/-O>(release_optimize)/d' \
        -i build/common.gypi

    # chromium uses hardcoded calls to ar, pkg-config, and it doesn't even always
    # respect its own AR_target variable. Fix this for multiarch by adding
    # appropriate symlinks here and adding this directory to the PATH
    local dir=${WORKBASE}/symlinked-build-tools
    edo mkdir -p ${dir}
    edo ln -s /usr/$(exhost --target)/bin/$(exhost --target)-pkg-config ${dir}/pkg-config
    edo ln -s /usr/$(exhost --target)/bin/$(exhost --target)-ar ${dir}/ar
    edo ln -s /usr/$(exhost --target)/bin/$(exhost --target)-cc ${dir}/gcc
    edo ln -s /usr/$(exhost --target)/bin/$(exhost --target)-c++ ${dir}/g++

    # and, they assume python is python2!
    edo ln -s /usr/$(exhost --target)/bin/python2 ${dir}/python
    export PATH="${dir}:${PATH}"

    # 46.0.2490.86 fails with Exception: Failed to open test/data/webui/i18n_process_css_test.html while
    # trying to flatten test/data/webui/i18n_process_css_test.html
    edo touch chrome/test/data/webui/i18n_process_css_test.html
}

# See http://code.google.com/p/chromium/wiki/LinuxBuildInstructions
inox_src_configure() {
    local myconf=(
        # Set up Google API keys, see http://www.chromium.org/developers/how-tos/api-keys
        # Note: These are for Exherbo use ONLY. For your own distribution, please get
        # your own set of keys.
        google_api_key=AIzaSyBEuNWzExJ_qIX-NT8OY_RGN6d6ZLWnExA
        google_default_client_id=750749113475.apps.googleusercontent.com
        google_default_client_secret=hw21UnHlcmzSMxzS6VACbPTq

        # Build against local system libraries instead of using a provided sysroot
        $(ever at_least 49 && echo use_sysroot=0 )

        # Disable the voice-recognition support (Ok Google) hotwords plugin. It downloads a binary
        # blob with which has access to the microphone, see debian bug #786909.
        enable_hotwording=0

        # Always available on amd64, no reason to force it on x86
        disable_sse2=$(option platform:amd64 0 $(option x86_cpu_features:sse2 0 1))

        disable_nacl=1

        no_strict_aliasing=1

        use_cups=$(option cups 1 0)
        use_gconf=$(option gconf 1 0)
        use_gnome_keyring=$(option keyring 1 0)
        use_pulseaudio=$(option pulseaudio 1 0)
        # hard disable kerberos support (requires heimdal)
        use_kerberos=0

        # Note: libmtp appears to be unused
        use_system_bzip2=1
        use_system_expat=1
        use_system_ffmpeg=0
        use_system_flac=1
        use_system_harfbuzz=1
        # our version is too recent; unicode/{bms,bmsearch,colldata}.h have been removed
        use_system_icu=0
        use_system_libevent=1
        # Note: We can choose between (B) bundled jpeg, (BT) bundled jpeg-turbo and (S{,T}) system jpeg{,-turbo}.
        # If the system jpeg lib is libjpeg-turbo we use it, otherwise we fall back to (BT).
        use_system_libjpeg=$(option providers:jpeg-turbo 1 0)
        # If use_system_libjpeg is enabled, use_libjpeg_turbo is ignored
        use_libjpeg_turbo=1
        use_system_libpng=1
        use_system_libsrtp=1
        # http://crbug.com/266149
        use_system_libusb=0
        # 46.0.2490.86: Build error with libvpx-1.5.0
        use_system_libvpx=0
        use_system_libwebp=1
        use_system_libxml=1
        use_system_libxslt=1
        use_system_minizip=1
        use_system_nspr=1
        use_system_opus=1
        # http://crbug.com/351093
        use_system_protobuf=0
        use_system_speex=1
        # http://crbug.com/22208
        use_system_sqlite=0
        use_system_v8=0
        use_system_xdg_utils=1
        use_system_yasm=1
        # Linking failure with system zlib
        use_system_zlib=0

        # Do not try using (bundled) gold
        linux_use_bundled_binutils=0
        linux_use_bundled_gold=0
        linux_use_gold_flags=0
        # Do not try using (bundled) clang
        clang=0
        host_clang=0

        # Link instead of using dlopen()
        linux_link_gnome_keyring=1
        linux_link_gsettings=1
        linux_link_libpci=1
        linux_link_libspeechd=1
        linux_link_pulseaudio=1

        # Tell chromium to look in the prefixed speech-dispatcher include directory, as is the
        # case for speechd[>=0.8]
        libspeechd_h_prefix='speech-dispatcher/'

        werror=
        disable_fatal_linker_warnings=1

        python_ver=$(python_get_abi)

        $(option platform:amd64 && echo target_arch=x64)
        $(option platform:x86 && echo target_arch=ia32)

        # gcc_version is actually the version of g++,
        # similarly changes to cflags affect C and C++ code
        $(cxx_is_gxx || echo gcc_version=unknown)

        # Build ffmpeg as a shared library
        ffmpeg_component=shared_library
        # Declare that we support H.264, etc.
        proprietary_codecs=$(option bindist 0 1)
        # Compile in H.264, etc.
        ffmpeg_branding=$(option bindist Chromium Chrome)

        # Disable HiDPI support until someone needs and can test it
        enable_hidpi=0

        # inox specific
		enable_webrtc=0
		enable_google_now=0
		enable_remoting=0
		safe_browsing_mode=0
		enable_rlz=0
		enable_hangout_services_extension=0
		branding=Chromium
		google_chrome_build=0
		enable_web_speech=1
		enable_wifi_bootstrapping=0
		enable_speech_input=0
		enable_pre_sync_backup=0
		enable_print_preview=0
    )

    if [[ ${CHROMIUM_CHANNEL} == "stable" ]]; then
        myconf+=(
            enable_pepper_cdms=1
            enable_widevine=1
        )
    fi

    local mc myconf_concat
    for mc in "${myconf[@]}"; do
        myconf_concat+="-D${mc} "
    done
    edo ./build/linux/unbundle/replace_gyp_files.py ${myconf_concat}

    # Pass --depth because of this:
    #   Exception: Could not automatically locate src directory.
    #   This is a temporary Chromium feature that will be removed.  Use --depth as a workaround.
    edo env GYP_GENERATORS=ninja build/gyp_chromium --depth "${WORK}" ${myconf_concat}
}

inox_src_compile() {
    eninja -C out/${BUILDTYPE} chrome chrome_sandbox
}

inox_src_test() {
    local disabled_base_tests=(
        FilePathTest.FromUTF8Unsafe_And_AsUTF8Unsafe            # Needs a utf8 locale
        LoggingTest.CheckStreamsAreLazy                         # does not like to be sandboxed
        OutOfMemoryDeathTest.ViaSharedLibraries
        ProcessMetricsTest.GetNumberOfThreads
        RTLTest.WrapPathWithLTRFormatting
        StatsTableTest.MultipleThreads                          # Flaky
        # Need access to a running X11 server (and potentially more)
        'MessageLoopTestTypeUI.*'
        MessageLoopTest.IsType
        'WaitableEventWatcherTest.*'
        'MessagePumpGLibTest.*'
        'MessagePumpLibeventTest.*'
        'TimerTest.*'
        # fails with "out of memory" even with plenty free mem
        SecurityTest.MemoryAllocationRestrictionsNew
        SecurityTest.MemoryAllocationRestrictionsNewArray
        SecurityTest.NewOverflow
        # Fails randomly on different systems
        SysInfoTest.MaxSharedMemorySize
        TraceEventTestFixture.TraceSampling
        # 42.0.2311.135
        ProcessUtilTest.CurrentDirectory
    )
    local disabled_crypto_tests=(
        # 39.0.2171.95
        SignatureVerifierTest.VerifyRSAPSS
    )
    local disabled_gn_tests=(
        BuilderTest.BasicDeps
        # 41.0.2272.76
        Label.Resolve
    )
    local disabled_ui_base_tests=(
        # Needs fonts/corefonts
        FontTest.LoadArial

        FontTest.GetActualFontNameForTesting

        # Need access to a running X11 server (and potentially more)
        'CanvasTest.*'
        'ClipboardTest.*'
        'ClipboardTest/0.*'
        'FontTest.AvgCharWidth'
        'FontTest.AvgWidths'
        'FontTest.Widths'
        'GtkExpandedContainerTest.*'
        'RenderTextTest.*'
        'ResourceBundleTest.DelegateGetFontList'
        'ScreenTest.*'
        'TextEliderTest.*'
        'TextUtilsTest.GetStringWidth'
        'AnimationContainerTest.*'
        'AnimationTest.*'
        'SlideAnimationTest.*'
        'OSExchangeDataProviderAuraX11Test.*'
        'InputMethodBaseTest.*'
        'OSExchangeDataTest.*'

        # These have been failing for a long time but are not critical. http://crbug.com/110711
        FontListTest.FontDescString_FromFontVector
        FontListTest.Fonts_DescStringWithStyleInFlexibleFormat_RoundTrip
        FontListTest.Fonts_FontVector_RoundTrip
        FontListTest.Fonts_FromDescString
        FontListTest.Fonts_FromDescStringInFlexibleFormat
        FontListTest.Fonts_FromDescStringWithStyleInFlexibleFormat
        FontListTest.Fonts_FromFontVector
        FontListTest.Fonts_GetHeight_GetBaseline
        FontListTest.Fonts_Derive
        FontListTest.Fonts_DeriveWithSizeDelta

        # 38.0.2125.101
        SelectionRequestorTest.NestedRequests
    )

    local disabled_media_tests=(
        # http://crbug.com/160384
        'YUVConvertTest.*'
    )

    local t suites=( base cacheinvalidation crypto gn gpu printing ui_base url ) HOME="${TEMP}"

    for t in ${suites[@]}; do
        tv=disabled_${t}_tests[*]
        eninja -C out/${BUILDTYPE} ${t}_unittests
        edo out/${BUILDTYPE}/${t}_unittests --gtest_filter=$(IFS=:; echo "-${!tv}")
    done
}

inox_src_install() {
    # Install into /opt
    local dest=/opt/inox
    edo cd out/${BUILDTYPE}

    exeinto ${dest}
    newexe chrome inox
    newexe chrome_sandbox chrome-sandbox # the name is hardcoded
    edo chmod 4755 "${IMAGE}"${dest}/chrome-sandbox
    doexe "${FILES}"/inox-launcher.sh

    insinto ${dest}
    doins -r *.pak locales resources
    doins icudtl.dat
    doins -r *.bin

    dosym /opt/netscape/plugins ${dest}

    if [[ ${CHROMIUM_CHANNEL} == "stable" ]]; then
        doins libwidevinecdmadapter.so
    fi

    dodir ${dest}/lib
    insinto ${dest}/lib
    doins lib/libffmpeg.so

    newman chrome.1 inox.1

    dodir /usr/$(exhost --target)/bin
    dosym ${dest}/inox-launcher.sh /usr/$(exhost --target)/bin/inox-browser

    for size in 22 24 48 64 128 256 ; do
        insinto /usr/share/icons/hicolor/${size}x${size}/apps
        newins "${WORK}"/chrome/app/theme/chromium/product_logo_${size}.png inox-browser.png
    done

    insinto /usr/share/applications/
    hereins inox-browser.desktop <<EOF
[Desktop Entry]
Version=1.0
Name=Inox
GenericName=Web Browser
Exec=inox-browser %U
Terminal=false
Icon=inox-browser
Type=Application
Categories=Network;WebBrowser;
MimeType=text/html;text/xml;application/xhtml_xml;x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ftp;x-scheme-handler/mailto;x-scheme-handler/webcal;
StartupWMClass=Inox-browser
EOF

    insinto /etc/revdep-rebuild
    hereins ${PN} <<EOF
SEARCH_DIRS=${dest}
EOF
}

inox_pkg_postinst() {
    freedesktop-desktop_pkg_postinst
    gtk-icon-cache_pkg_postinst
}

inox_pkg_postrm() {
    freedesktop-desktop_pkg_postrm
    gtk-icon-cache_pkg_postrm
}