# -*- 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           cmake 1.1
PortGroup           legacysupport 1.0

#==============================================================================
# IMPORTANT NOTE
#
# Before updating to a new version from upstream, please test building with
# +contrib, in addition to the default. Reason being, the extra functionality
# is used by many, including our own MacPorts members. Enough so that we may
# want to enable +contrib by default at some point.
#
# Also note that upstream has occassionally broken the Contrib build, so it's
# not a given that it will compile successfully.
#
# Net-Net: If upstream breaks Contrib for a certain release, please don't
# update to it. And submit a ticket for the issue, if none exists.
#
# Thanks!
#==============================================================================

name                opencv3-devel
conflicts           opencv3
set my_name         opencv3
version             3.4.16
# NOTE: Separate revisions maintained for Python subports, later in portfile
revision            22

categories          graphics science
license             BSD
maintainers         {mascguy @mascguy}

description         Open Source Computer Vision Library
long_description    OpenCV (Open Source Computer Vision Library) is an \
                    open source computer vision and machine learning \
                    software library. OpenCV was built to provide a \
                    common infrastructure for computer vision \
                    applications and to accelerate the use of machine \
                    perception in the commercial products. Being a \
                    BSD-licensed product, OpenCV makes it easy for \
                    businesses to utilize and modify the code.
homepage            https://opencv.org

master_sites        https://github.com/opencv/opencv/archive/:opencv
distname            ${version}
distfiles           ${distname}${extract.suffix}:opencv
dist_subdir         ${my_name}

# don't forget to also update the checksums under the contrib variant.
checksums-append \
                    ${distname}${extract.suffix} \
                    rmd160  c8c3c68a05b01d58505ca84e328996bbe17706b2 \
                    sha256  5e37b791b2fe42ed39b52d9955920b951ee42d5da95f79fbc9765a08ef733399 \
                    size    87694121

platform macosx {
    if {${os.major} <= 10} {
        # Build requires at least 10.7.3 SDK, even when targeting 10.6
        set lion_sdkpath ${developer_dir}/SDKs/MacOSX10.7.sdk
        if {[file exists $lion_sdkpath]} {
            configure.sdkroot $lion_sdkpath
        } else {
            pre-fetch {
                error "Building ${subport} @${version} on Mac OS X 10.6 requires the MacOSX10.7.sdk to be present in ${developer_dir}/SDKs/"
            }
        }
    }
}

#------------------------------------------------------------------------------
# Python build support
#------------------------------------------------------------------------------
set default_python_branch \
                    3.11
set default_python_version \
                    [join [lrange [split ${default_python_branch} .] 0 1] ""]
set default_python_path \
                    ${prefix}/bin/python${default_python_branch}

#------------------------------------------------------------------------------
# Subport name used for staging files, etc.
#
# This is needed to support Python subports, whose names have no relation to
# the actual physical file layout.
#
# NOTE: Presently, 'parent_subport_name' matches 'name'. HOWEVER, this will
#   change once the various OpenCV-related ports are merged.
#------------------------------------------------------------------------------
set parent_subport_name \
                    ${my_name}

worksrcdir          opencv-${version}

compiler.cxx_standard \
                    2011

compiler.blacklist-append \
                    cc \
                    *gcc* \
                    {clang < 800} \
                    {macports-clang-3.[0-9]} \
                    macports-clang-4.0

depends_build-append \
                    port:pkgconfig \
                    port:python${default_python_version}

depends_lib-append  \
                    path:lib/libavcodec.dylib:ffmpeg \
                    port:zlib \
                    port:bzip2 \
                    port:libpng \
                    path:include/turbojpeg.h:libjpeg-turbo \
                    port:openjpeg \
                    port:tiff \
                    port:webp \
                    port:ilmbase \
                    port:openexr2

# only search for openexr in ${prefix}
patchfiles-append   patch-find-openexr.diff

# recognize dylib as a valid library suffix
patchfiles-append   patch-dylib_suffix.diff

# do not find protobuf3-cpp header files if installed
configure.cppflags-replace -I${prefix}/include -isystem${prefix}/include
patchfiles-append   patch-local_protobuf.diff

post-patch {
    reinplace "s|@PREFIX@|${prefix}/libexec/openexr2|g" \
        ${worksrcpath}/cmake/OpenCVFindOpenEXR.cmake
}

# TODO: check and adapt those patches
#                    candidates/patch-modules_imgcodecs_src_grfmt_tiff.cpp.diff
#                    candidates/patch-modules_core_src_parallel.cpp.diff
#                    candidates/patch-modules-highgui-src-window_cocoa.mm.diff

# not currently used in the cmake build system:
#                     -DWITH_GTK_2_X=OFF
#                     -DWITH_NVCUVID=OFF
#                     -DCMAKE_VERBOSE=ON

#------------------------------------------------------------------------------
# CMake Variables
#
# When/if the CMake portgroup is extended to support more of these options,
# they can be replaced with those equivalents. For now, define them ahead of
# time, for later re-use.
#------------------------------------------------------------------------------

# Define all of our base paths up-front
set opencv_install_prefix \
                    ${prefix}/libexec/${parent_subport_name}
set opencv_install_cmake \
                    ${opencv_install_prefix}/cmake
set opencv_install_include \
                    ${prefix}/include/${parent_subport_name}
set opencv_install_lib \
                    ${prefix}/lib/${parent_subport_name}

# Populate the few CMake options currently available
# TODO: Extend CMake portgroup to support more paths
cmake.install_prefix \
                    ${opencv_install_prefix}
cmake_share_module_dir \
                    ${opencv_install_cmake}
cmake.install_rpath \
                    ${opencv_install_lib}

configure.args-append \
                    -DENABLE_CONFIG_VERIFICATION=OFF \
                    \
                    -DOPENCV_CONFIG_INSTALL_PATH=${opencv_install_cmake} \
                    -DOPENCV_BIN_INSTALL_PATH=${opencv_install_prefix}/bin \
                    -DOPENCV_SETUPVARS_INSTALL_PATH=${opencv_install_prefix}/scripts \
                    -DOPENCV_SBIN_INSTALL_PATH=${opencv_install_prefix}/sbin \
                    -DOPENCV_JAR_INSTALL_PATH=${opencv_install_prefix}/java/jar \
                    -DOPENCV_JNI_INSTALL_PATH=${opencv_install_prefix}/java/jni \
                    -DOPENCV_JNI_BIN_INSTALL_PATH=${opencv_install_prefix}/java/jni \
                    -DOPENCV_TEST_INSTALL_PATH=${opencv_install_prefix}/test/bin \
                    -DOPENCV_TEST_DATA_PATH=${opencv_install_prefix}/test/data \
                    -DOPENCV_SAMPLES_BIN_INSTALL_PATH=${opencv_install_prefix}/share/samples/bin \
                    -DOPENCV_SAMPLES_SRC_INSTALL_PATH=${opencv_install_prefix}/share/samples/src \
                    -DOPENCV_OTHER_INSTALL_PATH=${opencv_install_prefix}/share/data \
                    -DOPENCV_DOC_INSTALL_PATH=${opencv_install_prefix}/share/doc \
                    -DOPENCV_LICENSES_INSTALL_PATH=${opencv_install_prefix}/share/license \
                    -DOPENCV_INCLUDE_INSTALL_PATH=${opencv_install_include} \
                    -DOPENCV_LIB_INSTALL_PATH=${opencv_install_lib} \
                    -DOPENCV_3P_LIB_INSTALL_PATH=${opencv_install_lib}/3rdparty \
                    -DOPENCV_LIB_ARCHIVE_INSTALL_PATH=${opencv_install_lib}/static \
                    -DCMAKE_INSTALL_LIBEXECDIR=${opencv_install_prefix} \
                    -DCMAKE_INSTALL_BINDIR=${opencv_install_prefix}/bin \
                    -DCMAKE_INSTALL_SBINDIR=${opencv_install_prefix}/sbin \
                    -DCMAKE_INSTALL_SHAREDIR=${opencv_install_prefix}/share \
                    -DCMAKE_INSTALL_INCLUDEDIR=${opencv_install_include} \
                    -DCMAKE_INSTALL_LIBDIR=${opencv_install_lib} \
                    -DCMAKE_INSTALL_NAME_DIR=${opencv_install_lib} \
                    \
                    -DWITH_1394=OFF \
                    -DWITH_CARBON=OFF \
                    -DWITH_VTK=OFF \
                    -DWITH_CUDA=OFF \
                    -DWITH_CUFFT=OFF \
                    -DWITH_CUBLAS=OFF \
                    -DWITH_EIGEN=OFF \
                    -DWITH_FFMPEG=ON \
                    -DWITH_GSTREAMER=OFF \
                    -DWITH_GTK=OFF \
                    -DWITH_IPP=OFF \
                    -DWITH_JASPER=OFF \
                    -DWITH_JPEG=ON \
                    -DWITH_OPENJPEG=ON \
                    -DWITH_WEBP=ON \
                    -DWITH_OPENEXR=ON \
                    -DWITH_OPENGL=ON \
                    -DWITH_OPENNI=OFF \
                    -DWITH_OPENNI2=OFF \
                    -DWITH_PNG=ON \
                    -DWITH_PVAPI=OFF \
                    -DWITH_GIGEAPI=OFF \
                    -DWITH_QT=OFF \
                    -DWITH_QUICKTIME=OFF \
                    -DWITH_TBB=OFF \
                    -DWITH_OPENMP=OFF \
                    -DWITH_CSTRIPES=OFF \
                    -DWITH_PTHREADS_PF=OFF \
                    -DWITH_TIFF=ON \
                    -DWITH_UNICAP=OFF \
                    -DWITH_V4L=OFF \
                    -DWITH_LIBV4L=OFF \
                    -DWITH_XIMEA=OFF \
                    -DWITH_XINE=OFF \
                    -DWITH_CLP=OFF \
                    -DWITH_OPENCL=OFF \
                    -DWITH_OPENCL_SVM=OFF \
                    -DWITH_OPENCLAMDFFT=OFF \
                    -DWITH_OPENCLAMDBLAS=OFF \
                    -DWITH_INTELPERC=OFF \
                    -DWITH_MATLAB=OFF \
                    -DWITH_IPP_A=OFF \
                    -DWITH_VA=OFF \
                    -DWITH_VA_INTEL=OFF \
                    -DWITH_GDAL=OFF \
                    -DWITH_GPHOTO2=OFF \
                    \
                    -DBUILD_WITH_DEBUG_INFO=OFF \
                    -DBUILD_SHARED_LIBS=ON \
                    -DBUILD_opencv_apps=ON \
                    -DBUILD_DOCS=OFF \
                    -DBUILD_EXAMPLES=OFF \
                    -DBUILD_PACKAGE=OFF \
                    -DBUILD_PERF_TESTS=OFF \
                    -DBUILD_TESTS=OFF \
                    -DBUILD_WITH_DYNAMIC_IPP=OFF \
                    \
                    -DBUILD_ZLIB=OFF \
                    -DBUILD_TIFF=OFF \
                    -DBUILD_JASPER=OFF \
                    -DBUILD_JPEG=OFF \
                    -DBUILD_OPENJPEG=OFF \
                    -DBUILD_WEBP=OFF \
                    -DBUILD_PNG=OFF \
                    -DBUILD_OPENEXR=OFF \
                    -DBUILD_TBB=OFF \
                    -DBUILD_FFMPEG=OFF \
                    \
                    -DBUILD_opencv_java=OFF \
                    \
                    -DINSTALL_C_EXAMPLES=ON \
                    -DINSTALL_PYTHON_EXAMPLES=ON \
                    -DENABLE_PRECOMPILED_HEADERS=ON \
                    -DOPENCV_ENABLE_NONFREE=OFF \
                    -DENABLE_CXX11=ON \
                    \
                    -DBUILD_opencv_python2=OFF \
                    -DBUILD_opencv_python3=OFF \
                    -DOPENCV_PYTHON_SKIP_DETECTION=OFF \
                    -DPYTHON_EXECUTABLE=${default_python_path} \
                    -DPYTHON_DEFAULT_EXECUTABLE=${default_python_path}

if {![info exists universal_possible]} {
    set universal_possible [expr {${os.universal_supported} && [llength ${configure.universal_archs}] >= 2}]
}

platform darwin {
    configure.args-append \
                    -DZLIB_LIBRARY=${prefix}/lib/libz.dylib \
                    -DBZIP2_LIBRARIES=${prefix}/lib/libbz2.dylib

    # do not opportunistically find other LAPACK implementations
    # see cmake/OpenCVFindLAPACK.cmake
    configure.args-append \
                    -DLAPACK_IMPL=Apple \
                    -DLAPACK_LIBRARIES="-framework Accelerate" \
                    -DLAPACK_CBLAS_H=Accelerate/Accelerate.h \
                    -DLAPACK_LAPACKE_H=Accelerate/Accelerate.h

    # the AVFoundation backend is failing to build up to 10.8
    # it might be possible to work around or repair this on 10.7 and 10.8
    # there is also a qtkit video implementation prior to the AVFoundation version
    # that is about 2016 vintage. This could possibly be resuscitated if there
    # is motivation or interest in so doing
    if {${os.major} < 13} {
        configure.args-append \
                    -DWITH_AVFOUNDATION=OFF
    }

    if { ${configure.build_arch} in [list i386 ppc] || (${universal_possible} && [variant_isset universal] &&
        ("i386" in ${configure.universal_archs} || "ppc" in ${configure.universal_archs}))} {
        #The Accelerate ABI requires 32-bit signed integers.
        #In clapack.h, __CLPK_integer is a typedef for either
        #   int (64-bit) or long int (32-bit).
        #opencv only uses ints.
        #Casting between pointers is never recommended, but
        #   int and long int should have the same representations
        #   on 32-bit systems.
        patchfiles-append patch-32bit_accelerate.diff
    }

    # no thread-local storage
    # see https://trac.macports.org/ticket/53543
    if {${os.major} < 11} {
        configure.cppflags-append -DGOOGLE_PROTOBUF_NO_THREADLOCAL
    }
}

if { !${configure.ccache} } {
    configure.args-append \
        -DENABLE_CCACHE=NO
}

set opencv_linker_libs ""

# TODO: Actually fix this
if {[string match "*clang*" ${configure.compiler}]} {
    post-patch {
        reinplace "/-Werror=sequence-point/d" \
            ${worksrcpath}/cmake/OpenCVCompilerOptions.cmake
    }
}

# PCH broken when universal
if {${universal_possible} && [variant_isset universal]} {
    configure.args-replace  -DENABLE_PRECOMPILED_HEADERS=ON \
                            -DENABLE_PRECOMPILED_HEADERS=OFF
}

# Python Bindings
foreach python_branch {2.7} {
    set python_version   [join [lrange [split ${python_branch} .] 0 1] ""]
    set python_path      ${prefix}/bin/python${python_branch}
    set python_framework ${frameworks_dir}/Python.framework/Versions/${python_branch}
    set python_lib       ${prefix}/lib/libpython${python_branch}.dylib

    subport py${python_version}-${name} {
        # NOTE: Only rev-bump subports, for major changes/additions
        revision 5

        conflicts-append \
                            py${python_version}-opencv3

        depends_build-delete \
                            port:python${default_python_version}
        depends_lib-append \
                            port:${name} \
                            port:py${python_version}-numpy \
                            port:python${python_version}

        configure.args-replace \
                            -DBUILD_opencv_python2=OFF \
                            -DBUILD_opencv_python2=ON
        configure.args-replace \
                            -DBUILD_opencv_apps=ON \
                            -DBUILD_opencv_apps=OFF

        configure.args-replace \
                            -DPYTHON_EXECUTABLE=${default_python_path} \
                            -DPYTHON_EXECUTABLE=${python_path}
        configure.args-replace \
                            -DPYTHON_DEFAULT_EXECUTABLE=${default_python_path} \
                            -DPYTHON_DEFAULT_EXECUTABLE=${python_path}

        configure.args-append \
                            -DPYTHON2_EXECUTABLE=${python_path} \
                            -DPYTHON_LIBRARIES=${python_lib} \
                            -DPYTHON2_LIBRARIES=${python_lib} \
                            -DPYTHON2_INCLUDE_DIR=${python_framework}/Headers \
                            -DPYTHON2_PACKAGES_PATH=${python_framework}/lib/python${python_branch}/site-packages

        # Deconflict with parent port contents
        post-destroot {
            ui_debug "${subport}: python subport: removing files unrelated to Python bindings"
            foreach f [exec port -q contents ${name}] {
                delete ${destroot}${f}
            }
        }
    }
}

set python_branches {3.10 3.11}
foreach python_branch ${python_branches} {
    set python_version   [join [lrange [split ${python_branch} .] 0 1] ""]
    set python_path      ${prefix}/bin/python${python_branch}
    set python_framework ${frameworks_dir}/Python.framework/Versions/${python_branch}
    set python_lib       ${prefix}/lib/libpython${python_branch}.dylib

    subport py${python_version}-${name} {
        # NOTE: Only rev-bump subports, for major changes/additions
        revision 5

        conflicts-append \
                            py${python_version}-opencv3 \
                            py${python_version}-opencv4 \
                            py${python_version}-opencv4-devel

        depends_build-delete \
                            port:python${default_python_version}
        depends_lib-append \
                            port:${name} \
                            port:py${python_version}-numpy \
                            port:python${python_version}

        configure.args-replace \
                            -DBUILD_opencv_python3=OFF \
                            -DBUILD_opencv_python3=ON
        configure.args-replace \
                            -DBUILD_opencv_apps=ON \
                            -DBUILD_opencv_apps=OFF

        configure.args-replace \
                            -DPYTHON_EXECUTABLE=${default_python_path} \
                            -DPYTHON_EXECUTABLE=${python_path}
        configure.args-replace \
                            -DPYTHON_DEFAULT_EXECUTABLE=${default_python_path} \
                            -DPYTHON_DEFAULT_EXECUTABLE=${python_path}

        configure.args-append \
                            -DPYTHON3_EXECUTABLE=${python_path} \
                            -DPYTHON3_LIBRARY=${python_lib} \
                            -DPYTHON3_INCLUDE_DIR=${python_framework}/Headers \
                            -DPYTHON3_PACKAGES_PATH=${python_framework}/lib/python${python_branch}/site-packages

        # Deconflict with parent port contents
        post-destroot {
            ui_debug "${subport}: python subport: removing files unrelated to Python bindings"
            foreach f [exec port -q contents ${name}] {
                delete ${destroot}${f}
            }
        }
    }
}

if {${name} eq ${subport}} {
    notes \
        "* ${subport} binaries are now prefixed with '${my_name}_', to prevent conflicts\
        with other OpenCV-related ports." \
        "* Python bindings are now implemented via subports 'pyXX-${subport}',\
        to support multiple Python versions side-by-side."

    variant avx conflicts avx2 description {Enable AVX (and SSE4*) support} {
        configure.args-append \
                            -DENABLE_AVX=ON \
                            -DENABLE_SSE41=ON -DENABLE_SSE42=ON
    }

    variant avx2 conflicts avx description {Enable AVX, AVX2 (and SSE4*) support} {
        configure.args-append \
                            -DENABLE_AVX=ON -DENABLE_AVX2=ON \
                            -DENABLE_SSE41=ON -DENABLE_SSE42=ON
    }

    variant eigen description {Enable eigen support} {
        depends_lib-append  path:share/pkgconfig/eigen3.pc:eigen3
        configure.args-replace \
                            -DWITH_EIGEN=OFF \
                            -DWITH_EIGEN=ON
        configure.args-append \
                            -DEIGEN_INCLUDE_PATH=${prefix}/include/eigen3
    }

    variant opencl description {Enable OpenCL support} {
        pre-configure {
            if {${os.platform} eq "darwin" && ${os.major} < 11} {
                ui_error "The OpenCL variant only works with OS X 10.7 Lion or later."
                return -code error "incompatible OS X version"
            }
        }
        configure.args-replace \
                            -DWITH_OPENCL=OFF \
                            -DWITH_OPENCL=ON
    }

    variant openmp description {Include OpenMP support} {
        compiler.openmp_version 4.0
        configure.args-replace \
                            -DWITH_OPENMP=OFF \
                            -DWITH_OPENMP=ON
    }

    variant openni description {Enable OpenNI support} {
        depends_lib-append  port:openni
        patchfiles-append   patch-cmake_OpenCVFindOpenNI.cmake.diff
        configure.args-replace \
                            -DWITH_OPENNI=OFF \
                            -DWITH_OPENNI=ON

        post-patch {
             reinplace "s,@@PREFIX@@,${prefix},g" \
                 ${worksrcpath}/cmake/OpenCVFindOpenNI.cmake
        }
    }

    variant dc1394 description {Use libdc1394 for FireWire camera; breaks compatibility with Apple iSight FireWire camera} {
        depends_lib-append  port:libdc1394
        configure.args-replace \
                            -DWITH_1394=OFF \
                            -DWITH_1394=ON
        configure.args-append \
                            -DHAVE_DC1394_2=ON
    }

    variant qt4 conflicts qt5 description {Build with Qt4 Backend support} {
        PortGroup           qt4 1.0

        configure.args-replace \
                            -DWITH_QT=OFF \
                            -DWITH_QT=4
    }

    variant qt5 conflicts qt4 description {Build with Qt5 Backend support} {
        PortGroup           qt5 1.0

        configure.args-replace \
                            -DWITH_QT=OFF \
                            -DWITH_QT=5
    }

    variant java description {Add Java bindings} {
        PortGroup           java 1.0

        # OpenCV appears to support older Java versions,
        # and MacPorts users have requested Java 8 support:
        # see https://trac.macports.org/ticket/60193
        java.version        1.6+
        # Use latest LTS Java version as fallback
        java.fallback       openjdk11
        depends_build-append \
                            port:apache-ant
        configure.args-replace \
                            -DBUILD_opencv_java=OFF \
                            -DBUILD_opencv_java=ON
    }

    if {[variant_isset java] && ![variant_isset python27]} {
        configure.args-replace \
                            -DPYTHON_EXECUTABLE=OFF \
                            -DPYTHON_EXECUTABLE=${default_python_path}
        configure.args-delete \
                            -DBUILD_opencv_python2=OFF
    }

    variant tbb description {Use Intel TBB} {
        depends_lib-append  \
                            port:tbb
        configure.args-replace \
                            -DWITH_TBB=OFF \
                            -DWITH_TBB=ON
        configure.args-append \
                            -DHAVE_TBB=ON

        # NOTE: TBB 2020 (tbb port) doesn't provide cmake package and to prevent
        # from pickinkg OneTBB it uses TBBROO env to verify that cmake picks the right one
        configure.env-append \
                            TBBROOT=${prefix}/libexec/tbb
        configure.cflags-prepend \
                            -I${prefix}/libexec/tbb/include
        configure.cxxflags-prepend \
                            -I${prefix}/libexec/tbb/include
        configure.ldflags-prepend \
                            -L${prefix}/libexec/tbb/lib
    }

    variant vtk description {Include VTK support} {
        depends_lib-append  \
                            port:vtk
        configure.args-replace \
                            -DWITH_VTK=OFF \
                            -DWITH_VTK=ON
    }

    variant gdal description {Include GDAL support} {
        depends_lib-append \
                            port:gdal
        configure.args-replace \
                            -DWITH_GDAL=OFF \
                            -DWITH_GDAL=ON
    }

    variant contrib description {Build OpenCV with extra modules} {
        master_sites-append     https://github.com/opencv/opencv_contrib/archive:opencv_contrib
        distfiles-append        ${version}.zip:opencv_contrib
        checksums-append        ${version}.zip \
                                rmd160  1f4a256abf81291ba41e941b8519c160c4798963 \
                                sha256  46306034f3ebe3d245724f633df1b5ddde755266c95b2aaec76092f848fec7fb \
                                size    56441730

        configure.args-append \
                            -DOPENCV_EXTRA_MODULES_PATH=${workpath}/opencv_contrib-${version}/modules \
                            -DBUILD_PROTOBUF=YES
        depends_lib-append \
                            port:ceres-solver \
                            port:double-conversion \
                            port:gflags \
                            port:google-glog \
                            port:hdf5

        post-extract {
            # gunzip cannot handle multi-member .zip archives
            system "unzip -oq ${distpath}/${version}.zip -d ${extract.dir}"

            # less than ideal way for patchfiles to be applied to contrib directory
            ln -s ${workpath}/opencv_contrib-${version} ${worksrcpath}/opencv_contrib
        }

        extract.only        ${distname}${extract.suffix}
#                            ${version}.zip

        # dnn_modern:
        master_sites-append     https://github.com/tiny-dnn/tiny-dnn/archive/:tiny-dnn

        distfiles-append        v1.0.0a3.tar.gz:tiny-dnn

        checksums-append        v1.0.0a3.tar.gz \
                                rmd160  1d44a0f0c3b0a6f31a333afdfb246526c42336ad \
                                sha256  e2c61ce8c5debaa644121179e9dbdcf83f497f39de853f8dd5175846505aa18b \
                                size    12885646

        configure.args-append  -DOPENCV_TINY_DNN_URL=file://${distpath}/

        # xfeatures2d/boostdesc:
        master_sites-append    https://raw.githubusercontent.com/opencv/opencv_3rdparty/34e4206aef44d50e6bbcd0ab06354b52e7466d26:boostdesc

        distfiles-append   boostdesc_bgm.i:boostdesc \
                           boostdesc_bgm_bi.i:boostdesc \
                           boostdesc_bgm_hd.i:boostdesc \
                           boostdesc_binboost_064.i:boostdesc \
                           boostdesc_binboost_128.i:boostdesc \
                           boostdesc_binboost_256.i:boostdesc \
                           boostdesc_lbgm.i:boostdesc

        checksums-append   boostdesc_bgm.i \
                               rmd160 a090147b1ff8cdb23cbb3898cb5cd9cdb181f000 \
                               sha256 c441a027f15b9b8ff6c006b0775cd86781169ebd5b6257a94bdce668010d5df5 \
                               size 14852 \
                           boostdesc_bgm_bi.i \
                               rmd160 a4f858f29a638286065aba9a7cbddf25323b35b2 \
                               sha256 3d54b2934f0de963abbce985da303254ee78eebd05eb2af517105f9b0e670566 \
                               size 14864 \
                           boostdesc_bgm_hd.i \
                               rmd160 92cadac9bd2c73ffa014fb552480ee33bf252568 \
                               sha256 4b068631287f9914c3aa5bbdab76368b01493cea494ab47f7a70d2fa4f1c3e1b \
                               size 7832 \
                           boostdesc_binboost_064.i \
                               rmd160 6567930c5f8839bb8c877201ffed07b91edbdec3 \
                               sha256 090c9cc50663df3a91f2d7c704fa664493c96c39749b4cee9ebc29a20eb680d2 \
                               size 138093 \
                           boostdesc_binboost_128.i \
                               rmd160 5c9f9171ecb5100ab7390119a02d7dd072dd35de \
                               sha256 8f3622c1f3c0a14b1f1b7b955c518e97f7ccd0e9796e1dd9e7a975aad9bb2a22 \
                               size 275322 \
                           boostdesc_binboost_256.i \
                               rmd160 27a39257b04cad5143f369fccbea5dd495c219c0 \
                               sha256 a1c778059332b4904c9ce30ed888e9dd2e44621579362e6deb20ef4f4b0cf819 \
                               size 549754 \
                           boostdesc_lbgm.i \
                               rmd160 35efe18cb9449a41af2166255a23e29822aae4e9 \
                               sha256 42f6091199242fb6d96aec2f25644cd6f5e5f2fdddd1720f3422282e88cf3cd8 \
                               size 426280

        configure.args-append  -DOPENCV_BOOSTDESC_URL=file://${distpath}/

        #xfeatures2d/vggdesc:
        master_sites-append    https://raw.githubusercontent.com/opencv/opencv_3rdparty/fccf7cd6a4b12079f73bbfb21745f9babcd4eb1d:vggdesc

        distfiles-append   vgg_generated_48.i:vggdesc \
                           vgg_generated_64.i:vggdesc \
                           vgg_generated_80.i:vggdesc \
                           vgg_generated_120.i:vggdesc

        checksums-append   vgg_generated_48.i \
                               rmd160 fdb2d976ec287c4989e9d3b6f95104a0bef9c9a4 \
                               sha256 71274a67ab0896865e27de830eda0065e387d75fe071dab4a887e2430ccb8a35 \
                               size 773330 \
                           vgg_generated_64.i \
                               rmd160 1e4cbba9038c165d53d5e9c9bdd299cde54dbd3a \
                               sha256 2746c272af82b9a839a69de151c262be55d9ef8464b268001c33f99f9f5cebbe \
                               size 915012 \
                           vgg_generated_80.i \
                               rmd160 d950552c95026ae80c6fe5b9e30037104081cca2 \
                               sha256 08fbc8cb1686b6c45032a08c98f3857ead4755116410e16c68713f4dea4cbf5c \
                               size 1012932 \
                           vgg_generated_120.i \
                               rmd160 a8e2a8e88102871c4e7d75c1f8a474a006e90aaa \
                               sha256 f05e7eb7183ecbc788bfc26cea9db7dad8585178175411b93e444acdc8fb2048 \
                               size 1257733

        configure.args-append  -DOPENCV_VGGDESC_URL=file://${distpath}/

        #face:
        master_sites-append    https://raw.githubusercontent.com/opencv/opencv_3rdparty/8afa57abc8229d611c4937165d20e2a2d9fc5a12:face

        distfiles-append   face_landmark_model.dat:face

        checksums-append   face_landmark_model.dat \
                           rmd160 3a4e4a80f2c74a6af2b36b4d74e3c6d59c347ce0 \
                           sha256 eeab592db2861a6c94d592a48456cf59945d31483ce94a6bc4d3a4e318049ba3 \
                           size 72368157

        configure.args-append  -DOPENCV_FACE_ALIGNMENT_URL=file://${distpath}/
    }

    variant nonfree description {Include nonfree algorithms} {
        configure.args-replace \
                            -DOPENCV_ENABLE_NONFREE=OFF \
                            -DOPENCV_ENABLE_NONFREE=ON
    }

    variant tests description {Enable tests} {
        configure.args-replace \
                            -DBUILD_TESTS=OFF \
                            -DBUILD_TESTS=ON

        configure.args-replace \
                            -DBUILD_PERF_TESTS=OFF \
                            -DBUILD_PERF_TESTS=ON

        test.run            yes
        test.target         test
    }
}

# NOTE: Variant 'debug' is the only one that should be shared with Python subports
variant debug description {Build with debugging info} {
    configure.args-replace \
                            -DBUILD_WITH_DEBUG_INFO=OFF \
                            -DBUILD_WITH_DEBUG_INFO=ON
}

platform darwin {
    post-patch {
        if {${os.major} < 10} {
            reinplace "s:HAVE_GCD 1:HAVE_GCD 0:" \
                ${worksrcpath}/cmake/OpenCVFindLibsPerf.cmake
        }
    }
}

pre-configure {
    configure.args-append \
                            -DOPENCV_LINKER_LIBS=\"[join ${opencv_linker_libs} " "]\"
}

proc opencv_move_binaries {p_bin_main_dir p_bin_port_dir} {
    set bin_main_files \
        [glob -nocomplain -type f \
            -directory ${p_bin_main_dir} \
            *]
    ui_debug "opencv_move_binaries: bin_main_files: ${bin_main_files}"

    foreach f ${bin_main_files} {
        set fn [file tail ${f}]
        set f_dest "${p_bin_port_dir}/${fn}"
        ui_debug "opencv_move_binaries: moving file: ${f} -> ${f_dest}"
        move ${f} ${f_dest}
    }

    return 0
}

proc opencv_soft_link_binaries {p_bin_main_dir p_bin_port_dir p_destroot p_prefix p_subport} {
    set bin_prefix_old "opencv_"
    set bin_prefix_new "${p_subport}_"
    set bin_port_files \
        [glob -nocomplain -type f \
            -directory ${p_bin_port_dir} \
            *]
    ui_debug "opencv_soft_link_binaries: bin_port_files: ${bin_port_files}"

    # Links: Remove prefix 'opencv_', if any; add prefix '<subport>_'.
    foreach f ${bin_port_files} {
        set fn [file tail ${f}]
        set fn_new \
            [regsub ***=${bin_prefix_old} ${fn} ""]
        set f_dest \
            [regsub ***=${p_destroot} ${f} ""]
        set f_link \
            "${p_bin_main_dir}/${bin_prefix_new}${fn_new}"
        ui_debug "opencv_soft_link_binaries: soft-linking file: ${f_link} -> ${f_dest}"
        ln -s ${f_dest} ${f_link}
    }

    return 0
}

proc opencv_fix_pkgconfig {p_destroot p_prefix p_subport p_parent_subport_name} {
    if {${p_subport} eq ${p_parent_subport_name}} {
        set pkgconfig_file \
            "${p_destroot}${p_prefix}/lib/${p_parent_subport_name}/pkgconfig/opencv.pc"

        ui_debug "opencv_fix_pkgconfig: fixing pkgconfig file ${pkgconfig_file}"

        # Fix paths
        reinplace "s|\$\{exec_prefix\}\/||g" \
            ${pkgconfig_file}
        reinplace "s|\$\{prefix\}\/||g" \
            ${pkgconfig_file}

        # http://trac.macports.org/ticket/42702
        if {[variant_isset qt4] || [variant_isset qt5]} {
            reinplace "s|-L//System/Library/Frameworks ||g" \
                ${pkgconfig_file}
            reinplace "s|-lOpenGL.framework|-framework OpenGL|g" \
                ${pkgconfig_file}
        }
    }

    return 0
}

proc opencv_post_destroot {} {
    global destroot
    global prefix
    global subport
    global parent_subport_name

    opencv_fix_pkgconfig \
        ${destroot} \
        ${prefix} \
        ${subport} \
        ${parent_subport_name}

    set bin_main_dir \
        "${destroot}${prefix}/bin"
    set bin_port_dir \
        "${destroot}${prefix}/libexec/${parent_subport_name}/bin"

    # While the various configure-related options should catch everything, one or more
    # files may be missed. If so, ensure they're moved to the subport's bin area.
    opencv_move_binaries \
        ${bin_main_dir} \
        ${bin_port_dir}

    # Create soft links for binaries, each prefixed with '<parent_subport_name>_'.
    opencv_soft_link_binaries \
        ${bin_main_dir} \
        ${bin_port_dir} \
        ${destroot} \
        ${prefix} \
        ${parent_subport_name}
}

post-destroot {
    ui_debug "${subport}: phase post-destroot running"
    opencv_post_destroot
}

livecheck.type      regex
livecheck.url       https://opencv.org/releases/
livecheck.regex     {archive/(3\.[0-9.]+)?\.[tz]}
