# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4

PortSystem          1.0
PortGroup           active_variants 1.1
PortGroup           cmake   1.1
PortGroup           github  1.0
PortGroup           legacysupport 1.1
PortGroup           qt5     1.0
PortGroup           conflicts_build 1.0

name                qgis3
categories          gis
maintainers         {yahoo.com:n_larsson @nilason} {vince @Veence} openmaintainer
description         QGIS 3 is a user-friendly GIS based on Qt 5
long_description    QGIS is a full-featured, user-friendly, free-and-open-source \
                    (FOSS) geographical information system (GIS) that runs on    \
                    Unix platforms, Windows, and MacOS.

license             GPL-2+

homepage            https://www.qgis.org/

set name-ltr        qgis3-ltr
subport ${name-ltr} {}

if {${subport} eq ${name}} {
    # Latest version
    github.setup    qgis QGIS 3_44_4 final-
    github.tarball_from archive
    revision        0
    set app_name    QGIS3

    checksums       rmd160  75d7163605e327a9c4daf691009b0afd1749e4d8 \
                    sha256  1396c84dd6c9c89c026de8b564319e0f6206c8bbc1b160bfdc0fdf49adb61748 \
                    size    220521178
} else {
    # LTR version
    github.setup    qgis QGIS 3_40_12 final-
    github.tarball_from archive
    revision        0
    set app_name    QGIS3-LTR
    description     {*}${description} (LTR)

    checksums       rmd160  c726007917eaa9f445887b47728206fc5c9824ba \
                    sha256  34f2710ad993e6140edc6ed42b4f871a983c4ca7f4cbd82d15aec18502669bee \
                    size    213528630
}

# See: https://github.com/libspatialindex/libspatialindex/issues/276
conflicts_build     spatialindex

version             [string map {_ .} ${github.version}]

# Enable use of 'macports-libcxx' for macOS 10.14 and earlier, as port uses
# libcxx features normally only available on 10.15 and later.
legacysupport.newest_darwin_requires_legacy \
                    18
legacysupport.use_mp_libcxx \
                    yes

compiler.cxx_standard \
                    2017

# Fix build error related to header 'optional', added in Xcode 10:
#   src/core/annotations/qgsannotationlayerrenderer.cpp:23:10: fatal error: 'optional' file not found
#   #include <optional>
#            ^~~~~~~~~~
#compiler.blacklist-append \
#                    {clang < 1001}

# builds fail for 10.14/10.15, due to missing symbols
# See https://trac.macports.org/ticket/68181
compiler.blacklist-append \
                    {clang < 1200}

depends_build-append \
                    port:bison \
                    port:flex \
                    port:ld64

depends_lib-append  port:draco \
                    port:exiv2 \
                    port:expat \
                    port:gdal \
                    port:gdal-pdf \
                    port:geos \
                    port:gsl \
                    port:hdf5 \
                    port:libiconv \
                    port:libtasn1 \
                    port:libzip \
                    port:pdal \
                    port:proj \
                    port:protobuf3-cpp \
                    port:qca-qt5 \
                    port:qca-qt5-ossl \
                    port:qjson-qt5 \
                    port:qtkeychain-qt5 \
                    port:qwt-qt5 \
                    port:spatialite \
                    port:sqlite3 \
                    path:lib/libssl.dylib:openssl

qt5.depends_component \
                    qtscript \
                    qtscxml \
                    qtwebkit \
                    qtxmlpatterns \
                    sqlite-plugin

patchfiles-append   patch-app_info_plist_in.diff \
                    patch-CMakelists_txt.diff \
                    patch-MacBundleMacros.cmake.diff \
                    patch-SIPMacros.cmake.diff

post-patch {
    reinplace -E "s|@PREFIX@|${prefix}|g" \
        ${worksrcpath}/mac/app.info.plist.in

    # Handle QGIS Fix #11399 which doesn’t seem to work anymore
    reinplace -E "s|#ifdef Q_OS_MAC$|#if 0|" \
        ${worksrcpath}/src/app/layout/qgslayoutdesignerdialog.cpp

    reinplace -E "s|@APP_NAME@|${app_name}|" \
        ${worksrcpath}/CMakeLists.txt
}

cmake.install_prefix    ${applications_dir}

pre-configure {
    # Figure out HDF5's mpi include directory
    set mpl_include_dir ""
    if {![catch {set result [active_variants hdf5 openmpi]}]} {
        if {$result} {
            set mpl_include_dir "-I${prefix}/include/openmpi-mp"
        }
    }
    if {![catch {set result [active_variants hdf5 mpich]}]} {
        if {$result} {
            set mpl_include_dir "-I${prefix}/include/mpich-mp"
        }
    }
    if {$mpl_include_dir ne ""} {
        configure.cxxflags-append ${mpl_include_dir}
    }
}

configure.args-append \
                    -DAPPLE_APPKIT_LIBRARY=${configure.sdkroot}/System/Library/Frameworks/AppKit.framework \
                    -DAPPLE_APPLICATIONSERVICES_LIBRARY=${configure.sdkroot}/System/Library/Frameworks/ApplicationServices.framework \
                    -DAPPLE_COREFOUNDATION_LIBRARY=${configure.sdkroot}/System/Library/Frameworks/CoreFoundation.framework \
                    -DAPPLE_IOKIT_LIBRARY=${configure.sdkroot}/System/Library/Frameworks/IOKit.framework \
                    -DBUILD_WITH_QT6=OFF \
                    -DEXPAT_INCLUDE_DIR=${prefix}/include \
                    -DEXPAT_LIBRARY=${prefix}/lib/libexpat.dylib \
                    -DGDAL_CONFIG=${prefix}/bin/gdal-config \
                    -DGEOS_CONFIG=${prefix}/bin/geos-config \
                    -DLIBZIP_CONF_INCLUDE_DIR=${prefix}/lib/pkgconfig \
                    -DPROJ_ROOT=${prefix}/lib/proj9 \
                    -DQCA_INCLUDE_DIR=${prefix}/libexec/qt5/include/QtCrypto \
                    -DQCA_LIBRARY=${prefix}/libexec/qt5/lib/libqca-qt5.dylib \
                    -DQGIS_MACAPP_BUNDLE=0 \
                    -DQSCINTILLA_INCLUDE_DIR=${prefix}/libexec/qt5/include \
                    -DQSCINTILLA_LIBRARY=${prefix}/libexec/qt5/lib/libqscintilla2_qt5.dylib \
                    -DQT_LRELEASE_EXECUTABLE=${prefix}/libexec/qt5/bin/lrelease \
                    -DQWT_INCLUDE_DIR=${prefix}/libexec/qt5/lib/qwt.framework/Versions/Current/Headers \
                    -DQWT_LIBRARY=${prefix}/libexec/qt5/lib/qwt.framework/Versions/Current/qwt \
                    -DUSE_CCACHE=OFF \
                    -DUSE_OPENCL=ON \
                    -DWITH_3D=ON \
                    -DWITH_BINDINGS=FALSE \
                    -DWITH_DRACO=ON \
                    -DWITH_GRASS7=OFF \
                    -DWITH_GRASS8=OFF \
                    -DWITH_GSL=ON \
                    -DWITH_INTERNAL_QWTPOLAR=ON \
                    -DWITH_INTERNAL_SPATIALINDEX=ON \
                    -DWITH_PDAL=ON \
                    -DWITH_QSPATIALITE=OFF \
                    -DWITH_QWTPOLAR=ON \
                    -DWITH_SERVER=OFF

configure.cppflags-append \
                    -I${prefix}/lib/proj9/include
configure.ldflags-append \
                    "-Wl,-rpath,${prefix}/libexec/qt5/lib" \
                    -L${prefix}/lib/proj9/lib

# GRASS variants
variant grass7 conflicts grass description "Build GRASS 7 plugin" {
    depends_lib-append      port:grass7
    global grass_version
    set grass_version       78
    global grass_gis_base
    pre-configure {
        configure.args-replace  -DWITH_GRASS7=OFF -DWITH_GRASS7=ON
        configure.args-append   -DGRASS_PREFIX7=${grass_gis_base}
    }
    post-patch {
        reinplace "s|command = None|command = '${prefix}/bin/grass${grass_version}'|g" \
            ${worksrcpath}/python/plugins/grassprovider/grass_utils.py
    }
}

variant grass conflicts grass7 description "Build GRASS (latest) plugin" {
    depends_lib-append      port:grass
    global grass_gis_base
    pre-configure {
        set grass_gis_base      [exec ${prefix}/bin/grass --config path]
        configure.args-replace  -DWITH_GRASS8=OFF -DWITH_GRASS8=ON
        configure.args-append   -DGRASS_PREFIX8=${grass_gis_base}
    }
    post-patch {
        reinplace "s|command = None|command = '${prefix}/bin/grass'|g" \
            ${worksrcpath}/python/plugins/grassprovider/grass_utils.py
    }
}

# PostgreSQL variants
set pg_suffixes {17 16 15 14 13 12}
set pg_variants {}
foreach suffix ${pg_suffixes} {
    lappend pg_variants postgresql${suffix}
}
foreach suffix ${pg_suffixes} {
    set vrt postgresql${suffix}
    set pgversion [string index ${suffix} 0][string index ${suffix} 1]
    set index [lsearch -exact ${pg_variants} ${vrt}]
    set conf [lreplace ${pg_variants} ${index} ${index}]
    variant ${vrt} description "Use PostgreSQL ${pgversion}" conflicts {*}${conf} "
        depends_lib-append      port:${vrt}
        configure.args-append   -DPostgreSQL_ROOT=${prefix}/lib/${vrt} \
                                -DPostgreSQL_INCLUDE_DIR=${prefix}/include/${vrt}
        configure.env-append    PostgreSQL_ADDITIONAL_VERSIONS=15,16,17
    "
}
set pgdefault "if {"
foreach suffix ${pg_suffixes} {
    set pgdefault "${pgdefault}!\[variant_isset postgresql${suffix}\] && "
}
set pgdefault [string range ${pgdefault} 0 end-4]
set pgdefault "${pgdefault}} { default_variants +postgresql17 }"
eval ${pgdefault}

# Python variants
set python_suffixes {39 310 311 312 313}
set python_variants {}
set plugin_variants {}
foreach pyver ${python_suffixes} {
    lappend python_variants python${pyver}
    lappend plugin_variants plugin_support${pyver}
}
foreach pyver ${python_suffixes} {
    set vrt python${pyver}
    set pyversion [string index ${pyver} 0].[string range ${pyver} 1 end]
    set index [lsearch -exact ${python_variants} ${vrt}]
    set conf [lreplace ${python_variants} ${index} ${index}]

    variant ${vrt} description "Use Python ${pyversion} bindings" conflicts {*}${conf} "
        depends_lib-append      port:python${pyver} \
                                port:py${pyver}-pyqt5 \
                                port:py${pyver}-pyqt5-scintilla \
                                port:py${pyver}-gdal \
                                port:py${pyver}-six \
                                port:py${pyver}-protobuf3

        depends_build-append    port:py${pyver}-pyqt-builder \
                                path:${frameworks_dir}/Python.framework/Versions/${pyversion}/bin/sip-build:py${pyver}-sip

        depends_run-append      port:py${pyver}-psycopg2 \
                                port:py${pyver}-requests \
                                port:py${pyver}-owslib \
                                port:py${pyver}-yaml \
                                port:py${pyver}-jinja2 \
                                port:py${pyver}-pygments

        configure.env-append    PATH=${frameworks_dir}/Python.framework/Versions/${pyversion}/bin:$env(PATH)
        build.env-append        PATH=${frameworks_dir}/Python.framework/Versions/${pyversion}/bin:$env(PATH)
        destroot.env-append     PATH=${frameworks_dir}/Python.framework/Versions/${pyversion}/bin:$env(PATH)

        configure.args-append   -DPython_EXECUTABLE=${prefix}/bin/python${pyversion}
        configure.args-append   -DWITH_BINDINGS=ON
        configure.args-append   -DQSCI_SIP_DIR=${frameworks_dir}/Python.framework/Versions/${pyversion}/lib/python${pyversion}/site-packages/PyQt5/bindings

        if {\"${subport}\" eq \"${name-ltr}\"} {
            configure.args-append   -DPYUIC_PROGRAM=${prefix}/bin/pyuic5-${pyversion}
            configure.args-append   -DPYRCC_PROGRAM=${prefix}/bin/pyrcc5-${pyversion}
        }

        post-patch {
            # Complies with py-gdal layout
            set gdal_py_prefix \"${worksrcpath}/python/plugins/processing/algs/gdal\"
            foreach file    {\"AssignProjection\" \
                             \"fillnodata\" \
                             \"gdal2tiles\" \
                             \"gdal2xyz\" \
                             \"gdalcalc\" \
                             \"pansharp\" \
                             \"pct2rgb\" \
                             \"polygonize\" \
                             \"proximity\" \
                             \"retile\" \
                             \"rgb2pct\" \
                             \"sieve\" } {
                reinplace -E \"s|else \\\".py\\\"|else '.py-${pyversion}'|\" \${gdal_py_prefix}/\${file}.py
            }
            foreach file    {\"merge\"  } {
                if {\"${subport}\" eq \"${name-ltr}\"} {
                    reinplace -E \"s|else \\\".py\\\"|else '.py-${pyversion}'|\" \${gdal_py_prefix}/\${file}.py
                } else {
                    reinplace -E \"s|merge.command_ext()|'.py-${pyversion}'|\" \${gdal_py_prefix}/\${file}.py
                }
            }
        }
    "

    set vrt2 plugin_support${pyver}
    set index2 [lsearch -exact ${plugin_variants} ${vrt2}]
    set conf2 [lreplace ${plugin_variants} ${index2} ${index2}]

    variant ${vrt2} description "Add common Python ${pyversion} modules for QGIS plugins" conflicts {*}${conf2} "
        depends_run-append  port:py${pyver}-affine \
                            port:py${pyver}-cycler \
                            port:py${pyver}-dateutil \
                            port:py${pyver}-fiona \
                            port:py${pyver}-geojson \
                            port:py${pyver}-h5py \
                            port:py${pyver}-llvmlite \
                            port:py${pyver}-markupsafe \
                            port:py${pyver}-matplotlib \
                            port:py${pyver}-numpy \
                            port:py${pyver}-opencv4 \
                            port:py${pyver}-pandas \
                            port:py${pyver}-patsy \
                            port:py${pyver}-Pillow \
                            port:py${pyver}-plotly \
                            port:py${pyver}-pyproj \
                            port:py${pyver}-rasterio \
                            port:py${pyver}-rsgislib \
                            port:py${pyver}-scikit-learn \
                            port:py${pyver}-scipy \
                            port:py${pyver}-seaborn \
                            port:py${pyver}-shapely \
                            port:py${pyver}-sip \
                            port:py${pyver}-statsmodels \
                            port:py${pyver}-termcolor
    "
}

# Python default
set python_default "if {"
foreach pyver ${python_suffixes} {
    set python_default "${python_default}!\[variant_isset python${pyver}\] && "
}
set python_default [string range ${python_default} 0 end-4]
set python_default "${python_default}} { default_variants +python313}"
eval ${python_default}

# Python support default
set python_default "if {"
foreach pyver ${python_suffixes} {
    set python_default "${python_default}!\[variant_isset plugin_support${pyver}\] && "
}
set python_default [string range ${python_default} 0 end-4]
set python_default "${python_default}} { default_variants +plugin_support313}"
eval ${python_default}

pre-configure {
    # Assert +pythonXY and +plugin_supportXY variants are in sync
    set supp_py_list [list]
    set pyth_py_list [list]
    foreach pyver ${python_suffixes} {
        if {[variant_isset plugin_support${pyver}]} {lappend supp_py_list ${pyver}}
        if {[variant_isset python${pyver}]} {lappend pyth_py_list ${pyver}}
    }
    if { [expr ([llength $supp_py_list] > 0) && ([llength $pyth_py_list] > 0)] &&
         [lindex $supp_py_list 0] != [lindex $pyth_py_list 0] } {
             set pyv [lindex $pyth_py_list 0]
             ui_error "${subport} +pythonXY and +plugin_supportXY variants must be in sync"
             return -code error "Try running `port install ${subport} +python${pyv} +plugin_support${pyv}`"
    }
}

variant server description "Builds with the server (FCGI) option" {
    depends_lib-append      port:fcgi
    pre-configure {
        return -code error "The +server option is currently broken (doesn’t link properly)"
    }
    configure.args-replace  -DWITH_SERVER=OFF -DWITH_SERVER=ON
}

post-configure {
    # Workaround a bug in cmake???
    touch ${cmake.build_dir}/src/core/CMakeFiles/qgis_core.dir/build.make
    touch ${cmake.build_dir}/src/core/CMakeFiles/qgis_core_autogen.dir/build.make
}

post-destroot {
    # qgis_bench app doesn’t link properly. Who uses this anyway????
    delete ${destroot}${applications_dir}/${app_name}.app/Contents/MacOS/bin/qgis_bench.app
}

if {${subport} eq ${name-ltr}} {
    livecheck.type  regex
    livecheck.url   https://version.qgis.org/version-ltr.txt
    livecheck.version ${version}
    livecheck.regex #QGIS Version \[0-9\]{5}|Visit https://download.qgis.org to get your copy of version (\[0-9.\]+)|<html><body>
}

notes-append \
    "Some QGIS plugins may fail with error message noting missing PyQt5.QtWebKit\
    module, this could be solved by manually installing the module with e.g.\
    `sudo port install py313-pyqt5 +webkit` (just make sure you use the same Python\
    version for py-pyqt5 as for the QGIS Python bindings)."

notes-append \
    "Due to a bug `spatialindex` v2.1, the bundled version must be used for now.\
    `spatialindex` port may be activated after the installation of ${name} with `sudo port\
    activate spatialindex`. For this reason the ports\
    `py-pysal` and py-rtree` are removed from default dependencies, they may be added\
    by direct installation if needed."
