# Maintainer (arch): Alexander F. Rødseth <xyproto@archlinux.org>
# Contributor: loqs <bugs-archlinux@entropy-collector.net>
# Contributor: Gabriel Souza Franco <gabrielfrancosouza@gmail.com>
# Contributor: Florian Pritz
# Contributor: Jonas Heinrich <onny@project-insanity.org>
# Contributor: Jordi De Groof <jordi.degroof@gmail.com>
# Contributor: mickele
# Contributor: manwithgrenade
# Contributor: bricem13
# Contributor: gborzi
# Contributor: Adrian Insaurralde
# Maintainer: Parabola Hackers <dev@lists.parabola.nu>
# Contributor: bill-auger <bill-auger@programmer.net>


# parabola changes and rationale:
# libre:
#   - build without webengine (BR #1167)
#   - build without pip (BR #1035)
#   - disable downloader (BR #1035)
#   - add default session XML (BR #3522)
# technical:
#   - build from versioned source-ball rather than VCS sources
#   - pin to strongly-coupled dependency versions


pkgname=freecad
pkgver=0.21.2
pkgrel=16
pkgrel+=.parabola1
pkgdesc='Feature based parametric 3D CAD modeler'
arch=(x86_64)
arch+=(armv7h) # 'med-openmpi' is unavailable for i686
url='https://freecadweb.org/'
license=(LGPL)
depends=(boost-libs coin fmt glew jsoncpp libspnav med-openmpi netcdf
         opencascade openmpi pugixml pyside6 python-gitpython
         python-markdown python-matplotlib python-pip python-pivy python-ply
         python-yaml qt6-svg qt6-tools qt6-webengine
         xerces-c verdict)
depends=( ${depends[*]/python-pip/}    ) # build without pip
depends=( ${depends[*]/qt6-webengine/} ) # build without webengine
makedepends=(boost cgns cmake eigen git libharu liblas ninja openvdb openvr
             ospray pdal postgresql-libs python-mpi4py
             shiboken6 swig utf8cpp nlohmann-json)
makedepends=( ${makedepends[*]/git/} )                                  # build from source-ball
[[ "${CARCH}" == x86_64 ]] || makedepends=( ${makedepends[*]/ospray/} ) # unavailable for i686 and armv7h
optdepends=('graphviz: dependency graph support'
            'openscad: OpenSCAD support')
source=(${pkgname}-${pkgver}.tar.gz::https://github.com/${pkgname}/${pkgname}/archive/refs/tags/${pkgver}.tar.gz # build from source-ball
        freecad-vtk9.3.patch
        pyside6.patch
        62c3836c.patch
        https://github.com/FreeCAD/FreeCAD/commit/6043c904.patch)
source+=(branding.xml)
b2sums=('84a4f8008192cd1a2ee1737b537b2668a8c028aa8c8645e6e412ab9ef79bf3bdd2cb73d96fcfd2dbcff613cdcc59cbab95821406acdc9cd7d4eb4636c081be78'
        'f0b5a4648eb4befabb2339bae4e42044e436aa50ad1c2a25b243c965272a217b2c1c69c34d0d20bd01c573008de10f733b74857ffecac502b8558a7095e305e5'
        '63bfac252cc813f4e2454b4bbd8b0c55e2882566bd39bf1d0b812bafc305cad6b65293bad4f3c043b58df93a2c685e82e5853059335fe8e90531dcbc23e324e9'
        'eb474708c3611293cfe3dfc287418b606f7735f6eb306f44f7394cd7e65256daddcee35984211982f25064e7ec81cc038d4eeb8d34af7399058ecfb6e8e99e9f'
        'de4b98c4b488045f9810dce124c271d6f4f629922e026f2d4f1efd6c9060b92309db41f8e0f6ebe5e7a27399911ac908cc8935c2501214326dbb1c4b739d46cc')
b2sums+=('eb678f8bed6e11544bc7fb31205acbeaa0904c63d1828a0574900dcaeae453c7dacf5beaceeac5e2f951b8d46dfc5ae11ccd1b4a876f8809f81d76c71fc22e6a')


_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 epoch_rx='[0-9]+:'
  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

  echo -n "${constraint_string}"
}


prepare() {
  ln -fs FreeCAD-${pkgver} ${pkgname} # link source-ball root dir as VCS root dirname

  patch -d freecad -Np1 -i "$srcdir"/freecad-vtk9.3.patch
  patch -d freecad -Np1 -i ../62c3836c.patch # Fix Qt6 issues in addons manager
  patch -d freecad -Np1 -i ../pyside6.patch
  patch -d freecad -Np1 -i ../6043c904.patch # Fix build with Python 3.12
  sed -e 's|Shiboken::Module::getTypes(requiredModule)|reinterpret_cast<PyTypeObject **>(Shiboken::Module::getTypes(requiredModule))|' \
    -i freecad/src/Gui/PythonWrapper.cpp # Fix build with PySide 6.7
}

build() {
  local parabola_opts=( -D BUILD_ADDONMGR=OFF \
                        -D BUILD_WEB=OFF      )

  cmake \
    ${parabola_opts[*]} \
    -B build \
    -D BUILD_ENABLE_CXX_STD=C++17 \
    -D BUILD_FLAT_MESH=ON \
    -D FREECAD_QT_VERSION=6 \
    -D CMAKE_BUILD_TYPE=Release \
    -D CMAKE_C_FLAGS="$CFLAGS -ffat-lto-objects -fPIC -w" \
    -D CMAKE_CXX_FLAGS="$CXXFLAGS -ffat-lto-objects -fPIC -w" \
    -D CMAKE_INSTALL_BINDIR=/usr/lib/freecad/bin \
    -D CMAKE_INSTALL_DATADIR=/usr/share/freecad \
    -D CMAKE_INSTALL_DATAROOTDIR=/usr/share \
    -D CMAKE_INSTALL_DOCDIR=/usr/share/freecad/doc \
    -D CMAKE_INSTALL_LIBDIR=/usr/lib/freecad/lib \
    -D CMAKE_INSTALL_PREFIX=/usr/lib/freecad \
    -D FREECAD_USE_EXTERNAL_PIVY=ON \
    -D FREECAD_USE_OCC_VARIANT='Official Version' \
    -D FREECAD_USE_QT_FILEDIALOG=ON \
    -D PYTHON_EXECUTABLE=/usr/bin/python \
    -D INSTALL_TO_SITEPACKAGES=ON \
    -G Ninja \
    -S $pkgname \
    -W no-dev
  ninja -C build
}

package() {
  # pin to strongly-coupled dependency versions
  depends=( ${depends[*]/boost-libs/} $(_version_constraint boost-libs 3) )
  depends+=( $(_version_constraint opencascade 3) \
             $(_version_constraint python      2) )

  DESTDIR="$pkgdir" ninja -C build install

  # tools
  install -Dm755 $pkgname/src/Tools/{$pkgname-thumbnailer,fcinfo} -t "$pkgdir/usr/bin/"

  # symlinks
  install -d "$pkgdir/usr/bin"
  ln -sf /usr/lib/freecad/bin/FreeCAD "$pkgdir/usr/bin/freecad"
  ln -sf /usr/lib/freecad/bin/FreeCAD "$pkgdir/usr/bin/FreeCAD"
  ln -sf /usr/lib/freecad/bin/FreeCADCmd "$pkgdir/usr/bin/freecadcmd"
  ln -sf /usr/lib/freecad/bin/FreeCADCmd "$pkgdir/usr/bin/FreeCADCmd"

  # default session descriptor
  install -Dm644 branding.xml -t "$pkgdir/usr/lib/$pkgname/bin/"
}
