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

legacysupport.newest_darwin_requires_legacy 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!
#==============================================================================

# FIXME: this subport needs fixes which were earlier added to opencv4 subport.
set my_name         opencv4
name                ${my_name}-devel
conflicts           ${my_name}

github.setup        opencv opencv 4.13.0
revision            0
epoch               1
platforms           {darwin >= 10}
categories          graphics science
license             BSD
maintainers         {mascguy @mascguy} {@barracuda156 macos-powerpc.org:barracuda}

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
dist_subdir         ${my_name}
checksums           rmd160  0c4fbefd209153687b0fd7b8f6e5c49a904f2554 \
                    sha256  1d40ca017ea51c533cf9fd5cbde5b5fe7ae248291ddf2af99d4c17cf8e13017d \
                    size    95420275
github.tarball_from archive

#------------------------------------------------------------------------------
# Python build support
#------------------------------------------------------------------------------
set default_python_branch \
                    3.13
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}

patch.pre_args-replace  -p0 -p1

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

# use correct assembler syntax on ppc.
# this only adds a macro, no effect on other platforms.
patchfiles-append   patch-parallel_impl.cpp-cv_pause.diff

# https://github.com/opencv/opencv/issues/28553
patchfiles-append   patch-build-without-AVFoundation.diff

# Do not use incoherent optflags on PowerPC. This is inconsequential for other archs.
post-patch {
    reinplace "s|/usr/local/lib|${prefix}/lib|g" ${worksrcpath}/cmake/OpenCVCompilerOptions.cmake
    reinplace "s|-mcpu=G3 -mtune=G5|-mtune=native|" ${worksrcpath}/cmake/OpenCVCompilerOptimizations.cmake
}

# Claims to only need c++11 but actually uses at least c++14 features.
# core/cvstd_wrapper.hpp:45:40: warning: variable templates are a C++14 extension [-Wc++14-extensions]
set cxx_standard    2017
compiler.cxx_standard \
                    ${cxx_standard}
cmake.set_cxx_standard \
                    yes

compiler.blacklist-append \
                    {clang < 900}

depends_build-append \
                    port:cctools \
                    path:bin/pkg-config:pkgconfig \
                    port:python${default_python_version}

# TODO: Perhaps use a newer ffmpeg instead.
depends_lib-append  port:ade \
                    port:ffmpeg \
                    port:imath \
                    port:jasper \
                    port:libavif \
                    path:include/turbojpeg.h:libjpeg-turbo \
                    port:libjxl \
                    port:libpng \
                    port:libquirc \
                    port:libspng \
                    port:openexr \
                    port:openjpeg \
                    port:tiff \
                    port:webp \
                    port:zlib

#------------------------------------------------------------------------------
# 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 use by configure arguments.
#------------------------------------------------------------------------------

# 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:BOOL=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_ADE:BOOL=ON \
                    -Dade_DIR:PATH=${prefix}/share/ade/ \
                    \
                    -DHAVE_CXX11:BOOL=ON \
                    -DENABLE_CXX11:BOOL=ON \
                    \
                    -DBUILD_DOCS:BOOL=OFF \
                    -DBUILD_EXAMPLES:BOOL=OFF \
                    -DBUILD_opencv_apps:BOOL=ON \
                    -DBUILD_PERF_TESTS:BOOL=OFF \
                    -DBUILD_SHARED_LIBS:BOOL=ON \
                    -DBUILD_TESTS:BOOL=OFF \
                    -DBUILD_WITH_DEBUG_INFO:BOOL=OFF \
                    -DCV_TRACE:BOOL=OFF \
                    -DENABLE_PIC:BOOL=OFF \
                    -DINSTALL_C_EXAMPLES:BOOL=ON \
                    -DINSTALL_PYTHON_EXAMPLES:BOOL=ON \
                    \
                    -DENABLE_CCACHE:BOOL=OFF \
                    -DENABLE_PRECOMPILED_HEADERS:BOOL=ON \
                    \
                    -DENABLE_LTO:BOOL=OFF \
                    -DENABLE_THIN_LTO:BOOL=OFF \
                    -DOPENCV_ENABLE_MEMALIGN:BOOL=ON \
                    \
                    -DOPENCV_ENABLE_NONFREE:BOOL=OFF \
                    -DOPENCV_FORCE_3RDPARTY_BUILD:BOOL=OFF \
                    \
                    -DBUILD_FFMPEG:BOOL=OFF -DWITH_FFMPEG:BOOL=ON \
                    -DBUILD_JASPER:BOOL=OFF -DWITH_JASPER:BOOL=ON \
                    -DBUILD_JPEG:BOOL=OFF -DWITH_JPEG:BOOL=ON \
                    -DBUILD_OPENEXR:BOOL=OFF -DWITH_OPENEXR:BOOL=ON \
                    -DBUILD_OPENJPEG:BOOL=OFF -DWITH_OPENJPEG:BOOL=ON \
                    -DBUILD_PNG:BOOL=OFF -DWITH_PNG:BOOL=ON \
                    -DBUILD_TIFF:BOOL=OFF -DWITH_TIFF:BOOL=ON \
                    -DBUILD_WEBP:BOOL=OFF -DWITH_WEBP:BOOL=ON \
                    -DWITH_AVIF:BOOL=ON \
                    -DWITH_JPEGXL:BOOL=ON \
                    -DWITH_SPNG:BOOL=ON \
                    \
                    -DWITH_OPENCL:BOOL=OFF \
                    -DWITH_OPENCL_SVM:BOOL=OFF \
                    -DWITH_OPENCLAMDFFT:BOOL=OFF \
                    -DWITH_OPENCLAMDBLAS:BOOL=OFF \
                    \
                    -DWITH_LAPACK:BOOL=ON \
                    \
                    -DBUILD_IPP_IW:BOOL=OFF \
                    -DBUILD_ITT:BOOL=OFF -DWITH_ITT:BOOL=OFF \
                    -DBUILD_TBB:BOOL=OFF -DWITH_TBB:BOOL=OFF \
                    -DBUILD_ZLIB:BOOL=OFF \
                    -DWITH_1394:BOOL=OFF \
                    -DWITH_AVFOUNDATION:BOOL=ON \
                    -DWITH_ARAVIS:BOOL=OFF \
                    -DWITH_EIGEN:BOOL=OFF \
                    -DWITH_GDCM:BOOL=OFF \
                    -DWITH_GSTREAMER:BOOL=OFF \
                    -DWITH_GTK:BOOL=OFF \
                    -DWITH_HALIDE:BOOL=OFF \
                    -DWITH_HPX:BOOL=OFF \
                    -DWITH_INF_ENGINE:BOOL=OFF \
                    -DWITH_IPP:BOOL=OFF \
                    -DWITH_OPENGL:BOOL=OFF \
                    -DWITH_OPENMP:BOOL=OFF \
                    -DWITH_OPENNI:BOOL=OFF \
                    -DWITH_OPENNI2:BOOL=OFF \
                    -DWITH_OPENVX:BOOL=OFF \
                    -DWITH_PTHREADS_PF:BOOL=ON \
                    -DWITH_PVAPI:BOOL=OFF \
                    -DWITH_QT:BOOL=OFF \
                    -DWITH_VTK:BOOL=OFF \
                    -DWITH_VULKAN:BOOL=OFF \
                    -DWITH_XIMEA:BOOL=OFF \
                    -DWITH_ZLIB_NG:BOOL=OFF \
                    \
                    -DBUILD_JAVA:BOOL=OFF \
                    -DWITH_GDAL:BOOL=OFF \
                    -DWITH_GPHOTO2:BOOL=OFF \
                    -DWITH_IMGCODEC_GIF:BOOL=ON \
                    -DWITH_IMGCODEC_HDR:BOOL=ON \
                    -DWITH_IMGCODEC_PFM:BOOL=ON \
                    -DWITH_IMGCODEC_PXM:BOOL=ON \
                    -DWITH_IMGCODEC_SUNRASTER:BOOL=ON \
                    -DWITH_LIBREALSENSE:BOOL=OFF \
                    -DWITH_MFX:BOOL=OFF \
                    -DWITH_PROTOBUF:BOOL=OFF \
                    -DWITH_QUIRC:BOOL=ON -DHAVE_QUIRC:BOOL=ON \
                    -DWITH_VA:BOOL=OFF \
                    -DWITH_VA_INTEL:BOOL=OFF \
                    \
                    -DHAVE_COCOA:BOOL=ON \
                    \
                    -DBUILD_opencv_aruco:BOOL=ON \
                    \
                    -DBUILD_opencv_python2:BOOL=OFF \
                    -DBUILD_opencv_python3:BOOL=OFF \
                    -DOPENCV_PYTHON_SKIP_DETECTION:BOOL=OFF \
                    -DPYTHON_DEFAULT_EXECUTABLE:FILEPATH=${default_python_path} \
                    -DPYTHON_EXECUTABLE:FILEPATH=${default_python_path}

if {${name} eq ${subport}} {
    # generate pkg-config file
     configure.args-append \
                    -DOPENCV_GENERATE_PKGCONFIG=YES
}

universal_variant   no

# PCH broken when universal
# Keep around, for when universal support is fixed/enabled
if {![info exists universal_possible]} {
    set universal_possible [expr {${os.universal_supported} && [llength ${configure.universal_archs}] >= 2}]
}
if {${universal_possible} && [variant_isset universal]} {
    configure.args-replace \
                    -DENABLE_PRECOMPILED_HEADERS:BOOL=ON \
                    -DENABLE_PRECOMPILED_HEADERS:BOOL=OFF
}

if {${configure.ccache}} {
    configure.args-replace \
                    -DENABLE_CCACHE:BOOL=OFF \
                    -DENABLE_CCACHE:BOOL=ON
}

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

    # TODO: support OpenBLAS?
    # 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

    # Do not prohibit GTK:
    patchfiles-append patch-expose-gtk-choice.diff

    # 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 as 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} {
        ui_debug "AVFoundation not supported on this MacOS release; disabling"
        configure.args-replace \
                    -DWITH_AVFOUNDATION:BOOL=ON \
                    -DWITH_AVFOUNDATION:BOOL=OFF
    }

    if {${os.major} < 11} {
        patchfiles-append \
            patch-fix-cocoa.diff

        # There are invalid conversion errors in non-Eigen fallbacks which require -fpermissive:
        # essential_solver.cpp: error: invalid conversion from 'int*' to '__CLPK_integer*' {aka 'long int*'} [-fpermissive]
        # Unfortunately, enabling Eigen variant introduces another error:
        # /System/Library/Frameworks/vecLib.framework/Headers/vecLibTypes.h:69:26:
        # error: two or more data types in declaration of 'vBool32'
        configure.cxxflags-append \
            -fpermissive

        # FIXME!
        # opencv4_interactive-calibration and opencv4_visualisation binaries crash:
        # Program received signal EXC_BAD_ACCESS, Could not access memory.
        # Reason: KERN_PROTECTION_FAILURE at address: 0x00000000
        # 0x921d7c40 in std::codecvt<wchar_t, char, __mbstate_t>::do_unshift ()
        # The problem does not exist with 4.5.0, but by 4.13.0 it is broken.
        # Possibly related: https://github.com/clangen/musikcube/issues/658

        build.env-append    LC_ALL=C
        destroot.env-append LC_ALL=C
        test.env-append     LC_ALL=C

#         configure.optflags
#         configure.cflags-replace \
#             -Os -O0
#         configure.cxxflags-replace \
#             -Os -O0
    }
}

# Python Bindings
set python_branches {3.10 3.11 3.12 3.13 3.14}
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}

    subport py${python_version}-${name} {
        revision    0

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

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

        configure.args-replace \
                    -DBUILD_opencv_python3:BOOL=OFF \
                    -DBUILD_opencv_python3:BOOL=ON
        configure.args-replace \
                    -DBUILD_opencv_apps:BOOL=ON \
                    -DBUILD_opencv_apps:BOOL=OFF
        configure.args-replace \
                    -DBUILD_opencv_aruco:BOOL=ON \
                    -DBUILD_opencv_aruco:BOOL=OFF

        configure.args-replace \
                    -DPYTHON_EXECUTABLE:FILEPATH=${default_python_path} \
                    -DPYTHON_EXECUTABLE:FILEPATH=${python_path}
        configure.args-replace \
                    -DPYTHON_DEFAULT_EXECUTABLE:FILEPATH=${default_python_path} \
                    -DPYTHON_DEFAULT_EXECUTABLE:FILEPATH=${python_path}
        configure.args-append \
                    -DPYTHON3_EXECUTABLE=${python_path} \
                    -DPYTHON3_LIBRARY=${python_framework}/lib/libpython${python_branch}.dylib \
                    -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 {${subport} eq ${name}} {
    # Simple way does not work, see trickery below.
    # legacysupport.redirect_bins \
    #     opencv4_interactive-calibration opencv4_visualisation

    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 eigen description {Enable Eigen support} {
        depends_lib-append \
                    path:share/pkgconfig/eigen3.pc:eigen3
        configure.args-replace \
                    -DWITH_EIGEN:BOOL=OFF \
                    -DWITH_EIGEN:BOOL=ON
        configure.args-append \
                    -DEIGEN_INCLUDE_PATH:PATH=${prefix}/include/eigen3
    }

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

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

    variant lto description {Build with LTO} {
        # PortGroup  LTO 1.0

        configure.args-replace \
                    -DENABLE_LTO:BOOL=OFF \
                    -DENABLE_LTO:BOOL=ON
    }

    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:BOOL=OFF \
                    -DWITH_OPENCL:BOOL=ON
    }

    variant opengl description {Build with GL support} {
        configure.args-replace \
                    -DWITH_OPENGL:BOOL=OFF \
                    -DWITH_OPENGL:BOOL=ON
    }

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

    variant openni description {Enable OpenNI support} {
        depends_lib-append \
                    port:openni
        configure.args-replace  \
                    -DWITH_OPENNI:BOOL=OFF \
                    -DWITH_OPENNI:BOOL=ON
        configure.args-append \
                    -DOPENNI_INCLUDE_DIR:PATH=${prefix}/include/ni \
                    -DOPENNI_LIB_DIR:PATH=${prefix}/lib
    }

    variant ffmpeg5 conflicts ffmpeg6 ffmpeg7 ffmpeg8 description {Link against ffmpeg 5} {
        depends_lib-replace \
            port:ffmpeg port:ffmpeg5
        configure.env-append \
            PKG_CONFIG_PATH="${prefix}/libexec/ffmpeg6/lib/pkgconfig"
    }

    variant ffmpeg6 conflicts ffmpeg5 ffmpeg7 ffmpeg8 description {Link against ffmpeg 6} {
        depends_lib-replace \
            port:ffmpeg port:ffmpeg6
        configure.env-append \
            PKG_CONFIG_PATH="${prefix}/libexec/ffmpeg6/lib/pkgconfig"
    }

    variant ffmpeg7 conflicts ffmpeg5 ffmpeg6 ffmpeg8 description {Link against ffmpeg 7} {
        depends_lib-replace \
            port:ffmpeg port:ffmpeg7
        configure.env-append \
            PKG_CONFIG_PATH="${prefix}/libexec/ffmpeg7/lib/pkgconfig"
    }

    variant ffmpeg8 conflicts ffmpeg5 ffmpeg6 ffmpeg7 description {Link against ffmpeg 8} {
        depends_lib-replace \
            port:ffmpeg port:ffmpeg8
        configure.env-append \
            PKG_CONFIG_PATH="${prefix}/libexec/ffmpeg8/lib/pkgconfig"
    }

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

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

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

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

    variant gtk3 description {Build with GTK-3 Backend support} {
        patchfiles-append \
                    patch-disable-cocoa.diff

        depends_lib-append \
                    path:lib/pkgconfig/gtk+-3.0.pc:gtk3

        configure.args-replace \
                    -DHAVE_COCOA:BOOL=ON \
                    -DHAVE_COCOA:BOOL=OFF \
                    -DWITH_GTK:BOOL=OFF \
                    -DWITH_GTK:BOOL=ON
        configure.args-append \
                    -DBUILD_OBJC:BOOL=OFF
    }

    # TODO: if this makes sense without Java GUI, fix it properly.
    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.8
        # Use latest LTS Java version as fallback
        java.fallback   openjdk8
        depends_build-append \
                    port:apache-ant
        configure.args-replace \
                    -DBUILD_JAVA:BOOL=OFF \
                    -DBUILD_JAVA:BOOL=ON
    }

    # Can this finally be switched to OneTBB?
    variant tbb description {Use Intel TBB} {
        depends_lib-append \
                    port:tbb
        configure.args-replace \
                    -DWITH_TBB:BOOL=OFF \
                    -DWITH_TBB:BOOL=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:BOOL=OFF \
                    -DWITH_VTK:BOOL=ON
    }

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

        configure.args-replace \
                    -DBUILD_PERF_TESTS:BOOL=OFF \
                    -DBUILD_PERF_TESTS:BOOL=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:BOOL=OFF \
                    -DBUILD_WITH_DEBUG_INFO:BOOL=ON
}

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_parent_subport_name} {
    set pkgconfig_file \
        "${p_destroot}${p_prefix}/lib/${p_parent_subport_name}/pkgconfig/opencv4.pc"

    if {[file exists ${pkgconfig_file}]} {
        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}
    }

    return 0
}

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

    opencv_fix_pkgconfig \
        ${destroot} \
        ${prefix} \
        ${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 opencv4 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}
}

# Modify from _resources/port1.0/group/github-1.0.tcl to avoid file tag issue
proc move_gh_repo {repo_dir_patt new_name} {
    global distfiles workpath worksrcpath
    if {(![file exists ${worksrcpath}] || ![file exists ${workpath}/${new_name}]) && \
            [llength ${distfiles}] > 0 && \
            [llength [glob -nocomplain ${workpath}/*]] > 0} {
        if {[file exists [glob -nocomplain ${workpath}/${repo_dir_patt}]] && \
            [file isdirectory [glob -nocomplain ${workpath}/${repo_dir_patt}]]} {
            move [glob ${workpath}/${repo_dir_patt}] ${workpath}/${new_name}
        } else {
            # tarball is not "${repo_dir_patt}"
            ui_error "\n\nGitHub Extract Error: \${worksrcpath} does not exist after extracting\
                distfiles. This might indicate that the author or project is different than set\
                in the Portfile due to a rename at GitHub. Please examine the extracted directory\
                in ${workpath} and try to correct the Portfile by either changing the author or\
                project or adding the worksrcdir option with the correct directory name.\n"
            return -code error "Unexpected github tarball extract."
        }
    }
}

post-extract {
    move_gh_repo ${github.author}-${github.project}-* ${distname}
}

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

if {[string match "py*" ${subport}]} {
    livecheck.type  none
}
