_pkgver=$(curl -s 'https://gsdview.appspot.com/chromium-browser-official/?marker=chromium-28.0.1500.3.xz' | grep chromium-2 | tail -1 | cut -d '>' -f 2 | cut -d '/' -f 3 | cut -c 10-20)
# NOTE: These are run separately for build() and package() and thus not always the same, but pacman only tries to find the one of build(). Package has to be installed manually in that case.
_nacver=$(curl -s 'https://gsdview.appspot.com/nativeclient-archive2/toolchain/?marker=toolchain%2F11296%40' | grep -G '/[0-9]\{5\}/' | tail -1 | cut -d '>' -f3 | cut -c 1-5)
#_nacver=11296
#_pkgver=28.0.1500.3

_use_nacl=1
_use_libpdf=1
_use_pepperflash=1

_use_clang=0

pkgname='chromium-dev'
pkgver=${_pkgver}
pkgrel='1'
pkgdesc='The open-source project behind Google Chrome (Dev channel)'
arch=('i686' 'x86_64')
url='http://www.chromium.org/'
license=('BSD')
depends=('alsa-lib' 'desktop-file-utils' 'ffmpeg' 'gtk2' 'hicolor-icon-theme' 'libevent' 'libxslt' 'libxss'
         'minizip' 'nss' 'protobuf' 'speech-dispatcher' 'ttf-font' 'udev')
makedepends=('elfutils' 'gperf' 'mesa' 'python2-ply' 'python2-simplejson' 'subversion' 'xdg-utils' 'yasm')
install="${pkgname}".install
backup=('etc/chromium-dev/default')
noextract=(naclsdk_linux_x86.tgz
           naclsdk_pnacl_linux_x86.tgz
           naclsdk_pnacl_translator.tgz)
source=(http://commondatastorage.googleapis.com/chromium-browser-official/chromium-$pkgver.tar.xz
	http://gsdview.appspot.com/nativeclient-archive2/toolchain/$_nacver/naclsdk_linux_x86.tgz
	http://gsdview.appspot.com/nativeclient-archive2/toolchain/$_nacver/naclsdk_pnacl_linux_x86.tgz
	http://gsdview.appspot.com/nativeclient-archive2/toolchain/$_nacver/naclsdk_pnacl_translator.tgz
	http://gsdview.appspot.com/nativeclient-archive2/toolchain/$_nacver/naclsdk_pnacl_translator.tgz.sha1hash
        $pkgname.desktop
        $pkgname.sh
        default)
sha1sums=('a1325dd01ade989fc6b2ed4b7a4eee844e3100bc'
          '004d7496d7e08d96bb884748a9e55cd71cf78cee'
          '54c53502c26456c9735e67314b2d61e29477438e'
          'd6d2da45c0729dfd1c606a15c8ffb7591dbc7b44')
_google_api_key="AIzaSyDwr302FpOSkGRpLlUpPThNTDPbXcIn_FM"
_google_default_client_id="413772536636.apps.googleusercontent.com"
_google_default_client_secret="0ZChLK6AxeA3Isu96MkwqDR4"


if [ "${_use_pepperflash}" = "1" ] || [ "${_use_libpdf}" = "1" ]; then
    rm -f filelists.xml*

    [ "$CARCH" = "i686" ] && _rpm_arch='i386'
    [ "$CARCH" = "x86_64" ] && _rpm_arch='x86_64'
    wget -q "http://dl.google.com/linux/chrome/rpm/stable/"${_rpm_arch}"/repodata/filelists.xml.gz"
    gzip -d filelists.xml.gz
    _rpm_build="$(cat filelists.xml | grep -e "unstable" | cut -d \" -f12 | head -1)"
    _rpm_ver="$(cat filelists.xml | grep -e "unstable" | cut -d \" -f10 | head -1)"
    _rpm_sha1="$(cat filelists.xml | grep "unstable" | cut -d \" -f2 | head -1)"
    rm -f filelists.xml*
    source+=("http://dl.google.com/linux/chrome/rpm/stable/"${_rpm_arch}"/google-chrome-unstable-"${_rpm_ver}"-"${_rpm_build}"."${_rpm_arch}".rpm")
    sha1sums+=("${_rpm_sha1}")
    noextract+=("google-chrome-unstable-"${_rpm_ver}"-"${_rpm_build}"."${_rpm_arch}".rpm")
fi

_use_gnome=0
if [ -x /usr/bin/gconftool-2 ]; then
    depends+=('gconf' 'libgnome-keyring')
    _use_gnome=1
fi

_use_pulseaudio=0
if [ -x /usr/bin/pulseaudio ]; then
    depends+=('libpulse')
    _use_pulseaudio=1
fi

if [ "${_use_pepperflash}" = "1" ] && [ "${_use_nacl}" = "0" ]; then
    msg "To use PepperFlash you need to build chromium with NaCl!. Disabling PepperFlash support"
    _use_pepperflash=0
fi

build() {

    cd "${srcdir}"

    rm -rf chromium-build
    mv chromium-"${pkgver}" chromium-build
    cd chromium-build

    rm -rf third_party/WebKit/Source
    rm -rf v8
    rm -rf tools/gyp ; mkdir tools/gyp
    rm -rf third_party/skia/{include,src,gyp}
    rm -rf third_party/webrtc
    rm -rf third_party/libjingle/source ; mkdir third_party/libjingle/source

    # NOTE: These repositories were set up manually beforehand (obviously).
    pushd . &> /dev/null
    cd /media/LT/sources/blink/Source ; svn up -q
    cd /media/LT/sources/blink/Tools/DumpRenderTree ; svn up -q
    cd /media/LT/sources/s_v8 ; git pull origin master -q
    cd /media/LT/sources/hromium ; git pull origin trunk -q
    cd /media/LT/sources/native_client ; git pull origin master -q
    cd /media/LT/sources/gyp ; git pull origin master -q
    cd /media/LT/sources/skia/ ; git pull origin master -q
    cd /media/LT/sources/webrtc/ ; git pull origin master -q
    cd /media/LT/sources/libjingle/ ; svn up -q
    popd &> /dev/null

    cp -r /media/LT/sources/blink/Source third_party/WebKit/Source
    rm -rf third_party/WebKit/Source/.svn
    rm -rf third_party/WebKit/Tools/DumpRenderTree
    cp -r /media/LT/sources/blink/Tools/DumpRenderTree third_party/WebKit/Tools/DumpRenderTree
    mkdir v8 ; cp -a /media/LT/sources/s_v8/[^.]* v8
    cp -r /media/LT/sources/hromium/[^.]* .
    cp -r /media/LT/sources/webrtc/webrtc third_party/webrtc
    cp -r /media/LT/sources/native_client/[^.]* native_client/
    cp -r /media/LT/sources/gyp/[^.]* tools/gyp/
    cp -r /media/LT/sources/skia/{include,src,gyp} third_party/skia/
    cp -r /media/LT/sources/libjingle/[^.]* third_party/libjingle/source/
    rm -rf native_client/src/trusted/service_runtime/testdata
    rm -rf third_party/libjingle/source/talk/media/testdata
    rm -rf chrome/test/data
    mkdir chrome/test/data ; cp -r /media/LT/sources/hromium/chrome/test/data/nacl chrome/test/data/nacl
    rm -rf v8/test
    rm -rf gyp/test

    #msg "Compiler specific configuration..."
    if [ "${_use_clang}" = "1" ]; then
        msg2 "Download clang"
        sh ./tools/clang/scripts/update.sh
    fi

  msg "Configure to save configuration in ~/.config/${pkgname}"
  sed -e "s|'filename': 'chromium-browser'|'filename': 'chromium-dev'|" \
      -e "s|'confdir': 'chromium'|'confdir': 'chromium-dev'|" \
      -i chrome/chrome_exe.gypi
  sed -e 's|config_dir.Append("chromium")|config_dir.Append(\"chromium-dev\")|' \
      -e 's|config_dir.Append("chrome-frame")|config_dir.Append(\"chrome-frame-dev\")|' \
      -i chrome/common/chrome_paths_linux.cc

    msg "Remove unnecesary components"
    find third_party -type f \! -iname '*.gyp*' \
        \! -path 'third_party/angle/*' \
        \! -path 'third_party/cacheinvalidation/*' \
        \! -path 'third_party/cld/*' \
        \! -path 'third_party/cros_system_api/*'  \
        \! -path 'third_party/ffmpeg/*' \
        \! -path 'third_party/flot/*' \
        \! -path 'third_party/gold/*' \
        \! -path 'third_party/hunspell/*' \
        \! -path 'third_party/hyphen/*' \
        \! -path 'third_party/iccjpeg/*' \
        \! -path 'third_party/jsoncpp/*' \
        \! -path 'third_party/jstemplate/*' \
        \! -path 'third_party/khronos/*' \
        \! -path 'third_party/leveldatabase/*' \
        \! -path 'third_party/libjingle/*' \
        \! -path 'third_party/libphonenumber/*' \
        \! -path 'third_party/libsrtp/*' \
        \! -path 'third_party/libvpx/*' \
        \! -path 'third_party/libxml/chromium/*' \
        \! -path 'third_party/libXNVCtrl/*' \
        \! -path 'third_party/libyuv/*' \
        \! -path 'third_party/lss/*' \
        \! -path 'third_party/mesa/*' \
        \! -path 'third_party/modp_b64/*' \
        \! -path 'third_party/mongoose/*' \
        \! -path 'third_party/mt19937ar/*' \
        \! -path 'third_party/npapi/*' \
        \! -path 'third_party/openmax/*' \
        \! -path 'third_party/ots/*' \
        \! -path 'third_party/pywebsocket/*' \
        \! -path 'third_party/qcms/*' \
        \! -path 'third_party/re2/*' \
        \! -path 'third_party/sfntly/*' \
        \! -path 'third_party/skia/*' \
        \! -path 'third_party/smhasher/*' \
        \! -path 'third_party/snappy/*' \
        \! -path 'third_party/sqlite/*' \
        \! -path 'third_party/tcmalloc/*' \
        \! -path 'third_party/tlslite/*' \
        \! -path 'third_party/trace-viewer/*' \
        \! -path 'third_party/undoview/*' \
        \! -path 'third_party/v8-i18n/*' \
        \! -path 'third_party/webdriver/*' \
        \! -path 'third_party/WebKit/*' \
        \! -path 'third_party/webrtc/*' \
        \! -path 'third_party/widevine/*' \
        \! -path 'third_party/x86inc/*' \
        \! -path 'third_party/zlib/*' \
        -delete

    echo > "${srcdir}"/flapper_version.h

    patch -p1 -i $srcdir/../chromium-system-ffmpeg-r0.patch

    msg "Use python2"
  rm -rf "${srcdir}/python"
  mkdir "${srcdir}/python"
  ln -s /usr/bin/python2 "${srcdir}/python/python"
  export PATH="${srcdir}/python":$PATH
  find . -type f -exec sed -i -r -e 's|/usr/bin/python$|&2|g' -e 's|(/usr/bin/python2)\.4$|\1|g' {} \;


        msg "Prepare NaCl SDK"
        ln -s /usr/lib/nacl-toolchain-newlib native_client/toolchain/linux_x86_newlib
        mkdir native_client/toolchain/.tars
        ln -s "${srcdir}"/naclsdk_linux_x86.tgz native_client/toolchain/.tars
        ln -s "${srcdir}"/naclsdk_pnacl_linux_x86.tgz native_client/toolchain/.tars
        ln -s "${srcdir}"/naclsdk_pnacl_translator.tgz native_client/toolchain/.tars
        mkdir native_client/toolchain/pnacl_translator
        ln -s "${srcdir}"/naclsdk_pnacl_translator.tgz.sha1hash native_client/toolchain/pnacl_translator/SOURCE_SHA1

    msg "Build Chromium"
    [ "${CARCH}" = "i686" ] && _chromium_arch='ia32'
    [ "${CARCH}" = "x86_64" ] && _chromium_arch='x64'

    # CFLAGS are passed through release_extra_cflags below
    export -n CFLAGS CXXFLAGS

  _flags="-Ddisable_glibc=1
	  -Dffmpeg_branding=Chrome
          -Dflapper_version_h_file=${srcdir}/flapper_version.h
          -Dlibvpx_source=/usr/include
          -Dgoogle_api_key=${_google_api_key}
          -Dgoogle_default_client_id=${_google_default_client_id}
          -Dgoogle_default_client_secret=${_google_default_client_secret}
          -Dlinux_link_gsettings=1
          -Dlinux_link_libpci=1
          -Dlinux_link_libspeechd=1
          -Dlibspeechd_h_prefix=speech-dispatcher/
          -Dlinux_link_gnome_keyring=${_use_gnome}
          -Dlinux_sandbox_path=/usr/lib/chromium-dev/chromium-sandbox
          -Dlinux_sandbox_chrome_path=/usr/lib/chromium-dev/chromium
          -Dlinux_strip_binary=1
          -Dlinux_use_gold_binary=1
          -Dlinux_use_gold_flags=1
          -Dlinux_use_tcmalloc=1
          -Dno_strict_aliasing=1
          -Dproprietary_codecs=1
          -Drelease_extra_cflags=${CFLAGS}
          -Dremove_webcore_debug_symbols=1
          -Dtarget_arch=${_chromium_arch}
          -Dusb_ids_path=/usr/share/hwdata/usb.ids
          -Duse_gconf=0
          -Duse_gnome_keyring=${_use_gnome}
          -Duse_pulseaudio=0
          -Dwerror=
	  -Dbuild_ffmpegsumo=0"

  # NOTE: I use my own bleeding edge builds of eg. libvpx, libwebp, v8
  _flags+=" -Duse_system_bzip2=1
            -Duse_system_expat=1
            -Duse_system_ffmpeg=1
            -Duse_system_flac=1
            -Duse_system_harfbuzz=1
            -Duse_system_icu=1
            -Duse_system_libevent=1
            -Duse_system_libjpeg=1
            -Duse_system_libpng=1
            -Duse_system_libsrtp=0
            -Duse_system_libusb=1
            -Duse_system_libvpx=1
            -Duse_system_libwebp=1
            -Duse_system_libxml=1
            -Duse_system_libxslt=1
            -Duse_system_nspr=1
            -Duse_system_mesa=1
            -Duse_system_minizip=1
            -Duse_system_opus=1
            -Duse_system_protobuf=1
            -Duse_system_re2=0
            -Duse_system_snappy=0
            -Duse_system_speex=1
            -Duse_system_sqlite=0
            -Duse_system_ssl=0
            -Duse_system_v8=1
            -Duse_system_xdg_utils=1
            -Duse_system_yasm=1
            -Duse_system_zlib=0
	    -Duse_system_libexpat=1"

    _flags+=" -Dgcc_version=48"

  GYP_DEFINES="$(echo ${_flags} | sed 's|-D||g')"
  export GYP_DEFINES

  build/linux/unbundle/replace_gyp_files.py ${_flags}
  build/gyp_chromium --depth=.

    make BUILDTYPE=Release chrome chrome_sandbox chromedriver
    rm -rf $srcdir/chromium-build/third_party
}

package() {
  cd "${srcdir}/chromium-build"

  msg "Packaging ${pkgname}"
  install -Dm644 "${srcdir}/default" "${pkgdir}/etc/chromium-dev/default"
  install -Dm755 "${srcdir}/${pkgname}.sh" "${pkgdir}/usr/bin/${pkgname}"
  install -Dm755 out/Release/chrome "${pkgdir}/usr/lib/${pkgname}/chromium"
  install -Dm4755 -o root -g root out/Release/chrome_sandbox "${pkgdir}/usr/lib/${pkgname}/chromium-sandbox"
  install -Dm755 out/Release/chromedriver "${pkgdir}/usr/lib/${pkgname}/chromiumdriver"
  install -Dm644 out/Release/{chrome,chrome_100_percent,chrome_remote_desktop,content_resources,resources}.pak "${pkgdir}/usr/lib/${pkgname}"
  install -d "${pkgdir}/usr/lib/${pkgname}/locales"
  for i in out/Release/locales/*; do  install -Dm644 "$i" "${pkgdir}/usr/lib/${pkgname}/locales"; done
  install -Dm644 "${srcdir}/${pkgname}.desktop" "${pkgdir}/usr/share/applications/${pkgname}.desktop"
  install -Dm644 out/Release/chrome.1 "${pkgdir}/usr/share/man/man1/${pkgname}.1"
  install -Dm644 LICENSE "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
  for _size in 16 22 24 32 48 128 256; do
    case ${_size} in
      16|32) branding="chrome/app/theme/default_100_percent/chromium" ;;
      *) branding="chrome/app/theme/chromium" ;;
    esac
    install -Dm644 "${branding}/product_logo_${_size}.png" "${pkgdir}/usr/share/icons/hicolor/${_size}x${_size}/apps/${pkgname}.png"
  done

  # Install NaCL components
    msg2 "Adding NaCl components"
    install -Dm755 out/Release/libppGoogleNaClPluginChrome.so "${pkgdir}/usr/lib/${pkgname}/libppGoogleNaClPluginChrome.so"
    install -Dm755 out/Release/nacl_helper{,_bootstrap} "${pkgdir}/usr/lib/${pkgname}"
    [ "${CARCH}" = "i686" ] && install -Dm755 out/Release/nacl_irt_x86_32.nexe "${pkgdir}/usr/lib/${pkgname}"
    # NOTE: As of May 2013, this file somehow grows to 500 MiB!
    [ "${CARCH}" = "x86_64" ] && install -Dm755 out/Release/nacl_irt_x86_64.nexe "${pkgdir}/usr/lib/${pkgname}"

  # Extract and install PepperFlash
  if [ "${_use_pepperflash}" = "1" ]; then
    msg2 "Adding PepperFlash"
    cd "${srcdir}"
    bsdtar -xf "google-chrome-unstable-${_rpm_ver}-${_rpm_build}.${_rpm_arch}.rpm" opt/google/chrome/PepperFlash
    install -d "${pkgdir}/usr/lib/${pkgname}/PepperFlash"
    for i in "${srcdir}/opt/google/chrome/PepperFlash/"*; do install -Dm644 "$i" "${pkgdir}/usr/lib/${pkgname}/PepperFlash"; done
    chmod 775 "${pkgdir}/usr/lib/${pkgname}/PepperFlash/libpepflashplayer.so"
    rm -fr "${srcdir}/opt"
  fi

  # Extract and install libpdf.so
  if [ "${_use_libpdf}" = "1" ]; then
    msg2 "Adding libpdf"
    cd "${srcdir}"
    bsdtar -xf "google-chrome-unstable-${_rpm_ver}-${_rpm_build}.${_rpm_arch}.rpm" opt/google/chrome/libpdf.so
    install -Dm755 "${srcdir}/opt/google/chrome/libpdf.so" "${pkgdir}/usr/lib/${pkgname}/libpdf.so"
    rm -rf "${srcdir}/opt"
  fi
}