# Maintainer (aur): Fabio 'Lolix' Loli <fabio.loli@disroot.org>
# Contributor: Zen Wen <zen.8841@gmail.com>
# Contributor: Felix Yan <felixonmars@archlinux.org>
# Contributor: Antonio Rojas <arojas@archlinux.org>
# Contributor: Andrea Scarpino <andrea@archlinux.org>
# Maintainer: Parabola Hackers <dev@lists.parabola.nu>
# Contributor: bill-auger <bill-auger@programmer.net>


# parabola changes and rationale:
# - blacklist rescue for webengine clients which support webkit
# - pin to strongly-coupled dependency versions
# - conflict with newer 'icu' to protect dependents until this is rebuilt

# NOTE: Arch has no QT webkit. Parabola retains 'qt5-webkit' primarily
#       to support 'qutebrowser' and quassel's web-preview feature.
#       Qt5 and webkit are supported upstream; but that may change.
#       Watch https://github.com/qutebrowser/qutebrowser/issues/4039
#       especiallly, WRT movableink/webkit + mnutt/PyQt6-QtWebKit.

# NOTE: rebuild against each 'qt5-base' release vN.N.N - build order:
#         (qt5-base-N.N.N) <- qt5-webkit <- python-pyqt5 <- qutebrowser
#         (qt5-base-N.N.N) <- qt5-styleplugins

# NOTE: rebuild against each 'icu' release vN - dependents do not need rebuild


pkgname=qt5-webkit
_pkgver=5.212.0-alpha4
pkgver=${_pkgver/-/}
pkgrel=28
pkgrel+=.parabola1
arch=(x86_64 aarch64)
arch+=(armv7h i686)
url="https://github.com/qtwebkit/qtwebkit"
license=(LGPL-2.1-only)
# TODO: the licensing of 'qt5-webkit' is not clear  (needs review)
#       the AUR 'qt5-webkit' PKGBUILD has not yet migrated to SPDX
#       LGPL-2.1-only is only a guess - there is a LGPL2.1 file in the root dir;
#       but is not obvious which or if any files are covered by it
#       at least one license is not accounted for
#       (the BSD-like license from apple in many files)
pkgdesc="Classes for a WebKit2 based implementation and a new QML API"
source=("https://github.com/qtwebkit/qtwebkit/releases/download/qtwebkit-$_pkgver/qtwebkit-${_pkgver}.tar.xz"
        "https://src.fedoraproject.org/rpms/qt5-qtwebkit/raw/rawhide/f/qtwebkit-cstdint.patch"
        "https://src.fedoraproject.org/rpms/qt5-qtwebkit/raw/rawhide/f/qtwebkit-fix-build-gcc14.patch"
         https://src.fedoraproject.org/rpms/qt5-qtwebkit/raw/rawhide/f/webkit-offlineasm-warnings-ruby27.patch
         qt5-webkit-icu75.patch
         qt5-webkit-icu76.patch
         qt5-webkit-icu68.patch
         qt5-webkit-glib-2.68.patch
         qt5-webkit-python-3.9.patch
         qt5-webkit-bison-3.7.patch
)
depends=(qt5-location qt5-sensors qt5-webchannel libwebp libxcomposite gst-plugins-base hyphen woff2
         libicuuc.so libicui18n.so libxml2.so

         # namcap implicit depends
         glibc gcc-libs glib2 zlib libx11 sqlite gst-plugins-base-libs libjpeg-turbo icu libpng gstreamer libxml2
         qt5-base qt5-declarative)
makedepends=(cmake ruby ruby-erb gperf python qt5-doc qt5-tools)
makedepends=( ${makedepends[*]/qt5-doc/} ) # can not build - upstream deleted sources?
optdepends=('gst-plugins-good: Webm codec support')
options=(!lto)
sha256sums=('9ca126da9273664dd23a3ccd0c9bebceb7bb534bddd743db31caf6a5a6d4a9e6'
            '4c71c958eae45cae65c9f002024eb1369d06029b668e595158138ff7971e64f1'
            'eea38db22078700887bf22b6a49bb628fd8444cdb2e506770c993df883d0e8fb'
            '8768433ff3f641b506962ed22cc596eaf57bf21b6d3402e0e73ad8c2afeaa502'
            'b4d1ba1e99e28fd8cb1ec82252373c870ede683869a9cd43c8e465fe09531bcb'
            '2e360197a23c6274d7190113381ad497b2bba60bec5f627f987ad4113063c0d3'
            '0b40ed924f03ff6081af610bb0ee01560b7bd1fb68f8af02053304a01d4ccdf0'
            '4969dd03e482155e2490b50307dada81dda7bbc9e5398e3a53c20bc474f7c04e'
            '6e0cee08e4fa57b04752e80817f33562f48aa42608a3a620930b6040259b4932'
            '34f37b53ee0bc31c63ce85ebd1ae95543a8ba28483e387b20efd50574bd813be')


## dependency tweaks ##

# FIXME: Could NOT find Sqlite (missing: SQLITE_LIBRARIES)
# [[ "${CARCH}" == armv7h ]] && makedepends+=( 'pkgconf<=2.1.0' ) # dustbin 2024-01-31


## host tweaks ##

# webkit requires 2GB RAM per CPU
_CONSERVE_RESOURCES=$( [[ "$CARCH" =~ ^(armv7h)$ ]] ; echo $(( ! $? )) ; )
N_JOBS=4

(( _CONSERVE_RESOURCES )) && options=( !debug !strip )


_version_constraint() # (dep_pkgname [precision])
{
  Log() { [[ "${FUNCNAME[2]}" == package ]] && echo "$@" >&2 || : ; }

  PkgVersion()
  {
    if   [[ "${dep_pkgname}" =~ / ]]
    then pacman -S --print-format='%v' ${dep_pkgname} 2> /dev/null | tail -n 1
    else pacman -Ss ^${dep_pkgname}$ | head -n 1 | cut -d ' ' -f 2
    fi
  }


  local dep_pkgname=$1
  declare -i req_precision=$2
  local full_version=$(PkgVersion)
  local n_dots=$(tmp=${full_version%-*} ; tmp=${tmp//[^\.]} ; echo "${#tmp}" ;)
  local def_precision=$(( n_dots + 1 ))
  local is_prec_valid=$(( req_precision > 0 && req_precision <= def_precision ))
  local precision=$((( is_prec_valid )) && echo ${req_precision} || echo ${def_precision})
  local pkgver_rx='[0-9A-Za-z_]+'
  pkgver_rx=$(sed 's|\]|\+]|' <<<${pkgver_rx}) # according to the wiki, '+' is not allowed,
                                               # but some pkgver have it (eg: 5.15.10+kde+r130)
  local subver_rx='\.'${pkgver_rx}
  local pkgrel_rx='[0-9]+'
  local garbage_rx='[^0-9].*'
  local capture_rx=${pkgver_rx}
  for (( n_dots=1 ; n_dots < precision ; ++n_dots )) ; do capture_rx+=${subver_rx} ; done ;
  local epoch version pkgrel has_dot_char version_min version_max constraint_string
  declare -i subver subver_inc pkgrel_inc

  if   [[ "${full_version}" =~ ^(${epoch_rx})*(${capture_rx})(${subver_rx})*-(${pkgrel_rx}).*$ ]]
  then epoch=${BASH_REMATCH[1]}   # optional epoch
       version=${BASH_REMATCH[2]} # pkgver cut to the requested precision
       #unused=${BASH_REMATCH[3]} # discarded pkgver segments
       pkgrel=${BASH_REMATCH[4]}  # pkgrel with non-numerics right-trimmed
       has_dot_char=$([[ "${version}" =~ \. ]] ; echo $(( ! $? )) ; )
       subver=$(sed "s|${garbage_rx}||" <<<${version##*.}) # right-trim from any non-numeric
       version=$( (( has_dot_char )) && echo ${version%.*}.${subver} || echo ${subver} )
       version=${epoch}${version}
       subver_inc=$(( subver + 1 ))
       pkgrel_inc=$(( pkgrel + 1 ))
       version_min=$(   (( ! is_prec_valid    )) && echo ${full_version%-*}-${pkgrel} || \
                                                    echo ${version}                      )
       version_max=$( ( (( ! is_prec_valid    )) && echo ${full_version%-*}-${pkgrel_inc} ) || \
                      ( [[ "${version}" =~ \. ]] && echo ${version%.*}.${subver_inc}      ) || \
                                                    echo ${subver_inc}                         )
       constraint_string="${dep_pkgname}>=${version_min} ${dep_pkgname}<${version_max}"

       Log "Applied version constraint: '${constraint_string}'"
  else Log "ERROR: in _version_constraint() parsing: dep_pkgname='${dep_pkgname}' full_version='${full_version}'"
       exit 1
  fi

  unset -f Log PkgVersion

  echo -n "${constraint_string}"
}


prepare() {
  cd "qtwebkit-${_pkgver}"
  patch -p0 -i ../qt5-webkit-icu68.patch         # Fix build with ICU 68.x
  patch -p1 -i ../qt5-webkit-glib-2.68.patch     # https://github.com/qtwebkit/qtwebkit/issues/1057
  patch -p1 -i ../qt5-webkit-python-3.9.patch    # Fix build with python 3.9
  patch -p1 -i ../qt5-webkit-bison-3.7.patch     # Fix build with bison 3.7
  patch -p1 -i ../qtwebkit-cstdint.patch         # GCC 11.1
  patch -p1 -i ../qtwebkit-fix-build-gcc14.patch # GCC 14.1
  patch -p1 -i ../qt5-webkit-icu75.patch         # Fix build with ICU 75
  patch -p1 -i ../qt5-webkit-icu76.patch         # Fix build with ICU 76

  patch -Np1 -i ../webkit-offlineasm-warnings-ruby27.patch
  echo "Done patch for Ruby 3.2"
}

build() {
  local _flags=(
    -DCMAKE_CXX_FLAGS="${CXXFLAGS} -DNDEBUG"
    -DPORT=Qt
    -DUSE_LD_GOLD=OFF
    -DENABLE_XSLT=OFF
    -DENABLE_TOOLS=OFF
    -DPYTHON_EXECUTABLE:FILEPATH=/usr/bin/python
    -DCMAKE_POLICY_VERSION_MINIMUM=3.5
  )

  cmake -B build -S "qtwebkit-${_pkgver}" -Wno-dev \
    -DCMAKE_BUILD_TYPE=None \
    -DCMAKE_INSTALL_PREFIX=/usr \
    "${_flags[@]}"

  if (( _CONSERVE_RESOURCES )) ; then
    export CXXFLAGS+=' -fuse-ld=bfd'
    export LDFLAGS+=' -Wl,--no-keep-memory -Wl,--reduce-memory-overheads'
    cmake --build build -- -j${N_JOBS}
  else 
    cmake --build build
  fi
}

package() {
  # pin to strongly-coupled dependency versions
  depends+=( $(_version_constraint qt5-base 3) )
  depends+=( libxml2.so )

  # protect dependents (eg: quassel) from conflicting 'icu' linkages of 'qt5-webkit' and 'qt5-base'
  conflicts+=( "icu>=$(( $( ( _version_constraint icu 1 || : ) | cut -d '<' -f 2 ) + 1 ))" )

  DESTDIR="${pkgdir}" cmake --install build

  # "install" 'qt5-base' licenses
  install -d "$pkgdir"/usr/share/licenses
  ln -s /usr/share/licenses/qt5-base "$pkgdir"/usr/share/licenses/${pkgname}
}
