# Maintainer (arch): Bruno Pagani <archange@archlinux.org>
# Maintainer: Parabola Hackers <dev@lists.parabola.nu>


# parabola changes and rationale:
#  - build without qt6-webengine
#  - pin to strongly-coupled dependency versions
#  - build from source-ball rather than VCS
#  - build as split package ('jami-daemon'+'jami-qt' PKGBUILDs)
#    jami-{daemon,qt} versions are tightly inter-dependent;
#    so they always need rebuild together anyways
#    the release source-ball includes both;
#    so separate PKGBUILDs and build jobs are not necessary


pkgbase=jami
pkgname=(jami-daemon jami-qt)
pkgver=20240125.0
pkgrel=1
pkgrel+=.parabola1
pkgdesc="Free and universal communication platform which preserves the users’ privacy and freedoms (Qt client)"
arch=(x86_64)
arch+=(armv7h i686)
url="https://jami.net"
license=(GPL3)
groups=(jami)

depends=(glibc opendht gnutls nettle libgit2 libsecp256k1 libsecp256k1.so ffmpeg speexdsp
         fmt yaml-cpp jsoncpp zlib alsa-lib libpulse jack libupnp libnatpmp
         openssl webrtc-audio-processing systemd-libs libarchive) # daemon
depends+=(jami-daemon glib2 gdk-pixbuf2 libnm libnotify qrencode
          qt6-declarative qt6-multimedia qt6-svg qt6-5compat qt6-webengine
          qt6-webchannel qt6-shadertools) # client
depends=( ${depends[*]/qt6-webengine/} )
depends=( ${depends[*]/jami-daemon/} )
# depends+=( qt6-positioning )
makedepends=(git cmake perl asio msgpack-c msgpack-cxx restinio systemd meson) # daemon
makedepends+=(git cmake python qt6-networkauth qt6-tools) # client
makedepends=( ${makedepends[*]/git/} )

source=(https://ftp.gnu.org/gnu/jami/jami-${pkgver}.tar.gz{,.sig}
        qt-6.6.patch)
# _pjprojectver=311bd018fc07aaf62d4c2d2494e08b5ee97e6846 # 2023-10-19 (arch PKGBUILD)
# _pjprojectver=8d32e0b87ee3c747412be34fc9916a4e209f2e8f # 2024-01-08
_pjprojectver=e12ea3bfa81cc4f46031599f80707e81133f1353 # 2024-02-18
# _dhtnetver=fe79669b400d5e6a521fd1408dae02e0d4e50a5b # 2023-10-31 (arch PKGBUILD)
# _dhtnetver=41848a2c770d7eb0940d731014b81643f85e0d07 # 2024-01-22
_dhtnetver=18d344dce9bc9a683d73721a6efbc5cd8eb33828 # 2024-03-02
source+=(https://github.com/savoirfairelinux/pjproject/archive/${_pjprojectver}/pjproject-${_pjprojectver}.tar.gz
         dhtnet-$_dhtnetver.tar.gz::https://review.jami.net/plugins/gitiles/dhtnet/+archive/$_dhtnetver.tar.gz)
noextract=(pjproject-${_pjprojectver}.tar.gz
           dhtnet-${_dhtnetver}.tar.gz)
sha256sums=('27a5d689db39a5f23a1f57cc258898abdb56c3426c1a9280d3d1b2e96551c3f2' # 20240125.0
            'SKIP'
            '61d7ca804ed18650274f233cd60a811518859b4c6739ecc246414c35c4b8d906')
# sha256sums+=('7416e3879eb6c20b4a86f4bc86ca91053c580c7641a3f938a4a196183e9a80b4'  # 2024-01-08
#              '5b25af3dbd3a6f9c423062e58356e8e56f5bdeb9e342b79b2baf1ee623b3ee4d') # 2024-01-22
sha256sums+=('9e1e6362f144eaa743da79c6b818349eb188943e24e0553efd178a220346ab19'  # 2024-02-18
             '76ed18742c496814d2aa5e0f953a38adbd0e7c8b51ddb8be68bbdb8502d054ec') # 2024-03-02
validpgpkeys=('BE6273738E616D6D1B3A08E8A21A020248816103')


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


  local dep_pkgname=$1
  declare -i req_precision=$2
  local full_version=$(pacman -S --print-format='%v' ${dep_pkgname} 2> /dev/null | tail -n 1)
  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 version pkgrel has_dot_char version_min version_max constraint_string
  declare -i subver subver_inc pkgrel_inc

  if   [[ "${full_version}" =~ ^(${capture_rx})(${subver_rx})*-(${pkgrel_rx}).*$ ]]
  then version=${BASH_REMATCH[1]} # pkgver cut to the requested precision
       #unused=${BASH_REMATCH[2]} # discarded pkgver segments
       pkgrel=${BASH_REMATCH[3]}  # 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} )
       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

  echo -n "${constraint_string}"
}


prepare() {
  ## prepare daemon ##

  cd "${srcdir}"/${pkgbase}-${pkgver}/daemon

  cp "${srcdir}"/pjproject-${_pjprojectver}.tar.gz contrib/tarballs/
  cp "${srcdir}"/dhtnet-$_dhtnetver.tar.gz         contrib/tarballs/
  mkdir contrib/native


  ## prepare client ##

  cd "${srcdir}"/${pkgbase}-${pkgver}

  # Drop strict Qt version check. Qt is ABI stable and jami is not using any private API
  # corresponds to arch patch: 'drop-qt-version-check.patch'
  sed -i '/Qt build version mismatch!/d' src/app/mainapplication.cpp
  ! grep "Qt build version mismatch!"    src/app/mainapplication.cpp ||
  ! echo "ERROR: patches need re-working"                            || return 1

  # Workaround for running with Qt 6.6 https://git.jami.net/savoirfairelinux/jami-client-qt/-/issues/1397
  echo "applying qt-6.6.patch"
  patch -p1 < "${srcdir}"/qt-6.6.patch
}

build() {
  echo "building dependencies" # diff this section against 'jami-daemon' PKGBUILD
  cd "${srcdir}"/${pkgbase}-${pkgver}/daemon/contrib/native
  ../bootstrap \
      --disable-downloads \
      --disable-all \
      --enable-pjproject \
      --enable-dhtnet
  make DEPS_pjproject= DEPS_dhtnet=pjproject

  echo "building daemon" # diff this section against 'jami-daemon' PKGBUILD
  cd "${srcdir}"/${pkgbase}-${pkgver}/daemon
  arch-meson . build -D interfaces=library -D opensl=disabled -D portaudio=disabled \
                     $( ((CHECKFUNC)) && echo -D tests=true) \
                     -D pkg_config_path="${PWD}/contrib/$(cc -dumpmachine)/lib/pkgconfig"
  meson compile -C build

  echo "building client" # diff this section against 'jami-qt' PKGBUILD
  cd "${srcdir}"/${pkgbase}-${pkgver}
  cmake -B build -S ${pkgbase}-${pkgver} \
    -DCMAKE_INSTALL_PREFIX=/usr \
    -DCMAKE_BUILD_TYPE=Release \
    -DWITH_DAEMON_SUBMODULE=false \
    -DENABLE_LIBWRAP=OFF \
    -DWITH_WEBENGINE=false \
    -Wno-dev
  make -C build
}

package_jami-daemon() {
  : # TODO: fails to build
    # ../src/jamidht/archive_account_manager.cpp:660:29: error: ‘aesGetKey’ is not a member of ‘dht::crypto’
    # tried with the both of the unversioned external dependencies at the revisions the arch PKGBUILD uses
    # and also the revisions which were apparently current when the jami source-ball was made,
    # and also the current revisions today - all fail with same error
}

package_jami-qt() {
  # pin to current 'qt5-base' libs
  depends+=( $(_version_constraint 'qt5-base' 3) )
  replaces=(jami-gnome jami-libclient)
  conflicts=(jami-gnome jami-libclient)

  make -C build DESTDIR="${pkgdir}" install
}
