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

if {${subport} eq "phantomjs-qt-qtwebkit"} {
    github.setup    vitallium qtwebkit e7b74331d695bfa8b77e39cdc50fc2d84a49a22a
    # Change github.tarball_from to 'releases' or 'archive' next update
    github.tarball_from tarball
} else {
    github.setup    vitallium qtbase   b5cc0083a5766e773885e8dd624c51a967c17de0
    # Change github.tarball_from to 'releases' or 'archive' next update
    github.tarball_from tarball
}
name                phantomjs-qt

categories          aqua www
platforms           macosx
maintainers         {mcalhoun @MarcusCalhoun-Lopez} openmaintainer

# for OpenSSLException, see source and header files in src/network/ssl of qtbase
license             {LGPL-2.1 LGPL-3 GPL-3 OpenSSLException}

version             5.5.1

set qt5.custom_qt_name phantomjs-qt

PortGroup qt5_variables 1.0

# get Qt's version numbers
set branch          [join [lrange [split ${version} .] 0 1] .]
set qt_major        [lindex [split ${version} .] 0]

# Qt builds differently when it detects C++-11
compiler.cxx_standard 2011

# see https://bugreports.qt.io/browse/QTBUG-53656
# see https://github.com/ariya/phantomjs/issues/13930
if {${subport} ne ${name}} {
    fetch.type      git
}

############################################################################### TODO
#
# TODO: possible to trim dependencies of qtbase?
#
###############################################################################

############################################################################### Module Format
#
# "Qt Module Name" {
#     {
#         checksum, rmd160
#         checksum, sha256
#         checksum, size
#     }
#     dependencies, build
#     dependencies, lib
#     dependencies, Qt module name
#     Qt components provided
#     included in "standard" installation of Qt (empty string is no, explanation string is yes)
#     variant overrides
#     revision number
#     license replacement
# }
#
# module info found at https://doc.qt.io/archives/qt-5.5/qtmodules.html
#
###############################################################################
array set modules {
    qtbase {
        {
        }
        ""
        "port:zlib port:libpng path:include/turbojpeg.h:libjpeg-turbo path:lib/pkgconfig/icu-uc.pc:icu port:pcre port:openssl10 port:fontconfig port:freetype"
        ""
        {"Qt Core"}
        ""
        "variant overrides: ~docs ~examples"
        "revision 5"
        "License: "
    }
    qtwebkit {
        {
        }
        "port:python27 port:bison"
        "port:fontconfig path:lib/pkgconfig/icu-uc.pc:icu port:leveldb port:webp port:libxml2 port:libxslt port:zlib port:sqlite3"
        "qtbase"
        {"Qt WebKit" "Qt WebKit Widgets"}
        ""
        "variant overrides: ~docs ~examples"
        "revision 8"
        "License: "
    }
}

############################################################################### SQL Plugin Format
#
# {
#     variant name
#     dependency, library
#     include path
#     link requirement
#     obsolete? (empty string is no)
# }
#
###############################################################################
array set sql_plugins {
    {sqlite SQLite "revision 0"} {
        {
            "sqlite3"
            "port:sqlite3"
            "${prefix}/include"
            "-L${prefix}/lib -lsqlite3"
            ""
        }
    }
}

# because CPATH is set, pkgconfig does not include ${prefix}/lib and ${prefix}/include even when requested
# this means that files in ${prefix}/lib and ${prefix}/include are the *last* to be found
# this causes problems when there are files in ${worksrpath} that are unintentionally found instead
configure.env-append \
    PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 \
    PKG_CONFIG_ALLOW_SYSTEM_LIBS=1
build.env-append \
    PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 \
    PKG_CONFIG_ALLOW_SYSTEM_LIBS=1

# Qt uses CFRunLoopTimerCreateWithHandler, which was not introduced until Mac OS X 10.7
# see https://developer.apple.com/reference/corefoundation/1542555-cfrunlooptimercreatewithhandler?language=objc
if { ${os.platform} eq "darwin" && ${os.major} < 11 } {
    known_fail  yes
    pre-fetch {
        ui_error "${subport} requires OS X 10.7 or later"
        return -code error "incompatible OS version"
    }
}

foreach {module module_info} [array get modules] {

    set revision_string [string trim [lindex ${module_info} 7]]
    set revision_string [string range ${revision_string} 1+[string last " " ${revision_string}] end]

    subport ${name}-${module} {

        distname        ${module}-opensource-src-${version}

        revision ${revision_string}

        # see https://bugreports.qt.io/browse/QTBUG-35514
        build.target

        set license_string [lindex ${module_info} 8]
        set license_string [string range ${license_string} 1+[string first ":" ${license_string}] end]
        set license_string [string trim  ${license_string}]

        if { ${license_string} ne "" } {
            license {*}${license_string}
        }

        foreach deps [lindex ${module_info} 1] {
            depends_build-append [subst ${deps}]
        }

        foreach deps [lindex ${module_info} 2] {
            depends_lib-append [subst ${deps}]
        }

        foreach qtdeps [lindex ${module_info} 3] {
            if { ${qtdeps} ne "qtbase" } {
                depends_lib-append port:${name}-${qtdeps}
            }
        }

        description       Tools and Module(s) for Qt Tool Kit ${qt_major}

        set modules_provided_list [lindex ${module_info} 4]
        if { [llength ${modules_provided_list}] == 1 } {
            set modules_provided_join [lindex ${modules_provided_list} 0]
        } elseif { [llength ${modules_provided_list}] == 2 } {
            set modules_provided_join [join ${modules_provided_list} " and "]
        } else {
            set modules_provided_join [join [list [join [lrange ${modules_provided_list} 0 end-1] ", "] [lindex ${modules_provided_list} end]] ", and "]
        }

        long_description  "Tools and Module(s) for Qt Tool Kit ${qt_major}: ${modules_provided_join}"

        if { ${module} eq "qtbase" } {
            # this subport uses configure script (NOT qmake)
            PortGroup           qt5 1.0

            if { ${os.platform} ne "darwin" } {
                pre-fetch {
                    ui_warn "${subport} is untested on \"${os.platform}\"."
                }
            }

            if {${universal_possible} && [variant_isset universal]} {
                pre-fetch {
                    ui_warn "Multiple architectures is not a Reference Configuration for Qt."
                    ui_warn "See https://doc.qt.io/qt-5/supported-platforms.html#reference-configurations"
                }
            } else {
                if { ${configure.build_arch} eq "i386" } {
                    pre-fetch {
                        ui_warn "32-bit mode is not a Reference Configuration for Qt."
                        ui_warn "See https://doc.qt.io/qt-5/supported-platforms.html#reference-configurations"
                    }
                }
            }

            # upstream patches
            patchfiles-append patch-upstream.diff

            # https://codereview.qt-project.org/#/c/141654/
            patchfiles-append patch-add_sdk.diff

            # the build system uses pkgconfig to look for an OpenGL installation (gl.pc)
            # the build system automatically uses OpenGL frameworks (-framework OpenGL -framework AGL)
            # if mesa is installed, the build system will try to use both OpenGL systems
            # when building qtmultimedia, this will cause problems
            #    Undefined symbols: "_CGLGetCurrentContext"
            patchfiles-append patch-opengl.diff

            # see https://codereview.qt-project.org/#/c/126584/
            patchfiles-append patch-pcfiles.diff

            # https://codereview.qt-project.org/#/c/140876/
            patchfiles-append patch-stdloc.diff

            #https://codereview.qt-project.org/#/c/138349
            patchfiles-append patch-rpath.diff

            # see https://stackoverflow.com/questions/14506151/invalid-symbol-redefinition-in-inline-asm-on-llvm
            # only runs test code on 32-bit systems
            patchfiles-append patch-tst_benchlibcallgrind.diff

            # this test might still cause problems, but with 5.4.2->5.5.0, it is no longer run
            # tests/auto/corelib/plugin/qpluginloader/qpluginloader.pro:
            #     -macx-*: SUBDIRS += machtest
            #     +macx-*: contains(QT_CONFIG, private_tests): SUBDIRS += machtest
            #
            # When testing, ensure that a universal object file is not inadvertently created.
            patchfiles-append patch-machtest.diff

            # see #52200
            # see https://codereview.qt-project.org/#/c/164673/
            patchfiles-append patch-xcrun.diff

            # see https://bugreports.qt.io/browse/QTBUG-62266
            patchfiles-append patch-sdk10_13.diff

            # avoid non-standard C++ that Xcode Clang accepts but other compilers do not
            # see https://lists.llvm.org/pipermail/llvm-bugs/2017-January/053481.html
            # see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=11764
            patchfiles-append patch-qualified_reference.diff

            # find the Rez program
            patchfiles-append patch-find_rez.diff
            post-patch {
                reinplace \
                    "s|__MACPORTS_Rez__|[exec -ignorestderr xcrun --find Rez]|g" \
                    mkspecs/common/mac.conf \
                    mkspecs/features/mac/rez.prf
            }

            # Qt assumes Clang's x86intrin.h does not provide _bit_scan_reverse
            # this assumption is incorrect for Clang 9.0 and later
            # (which Xcode 11.4 and later are also based on)
            #     see https://github.com/llvm/llvm-project/commit/88f4054f48c5
            # see https://trac.macports.org/ticket/59364 https://trac.macports.org/ticket/62051
            patchfiles-append patch-qtbase-intel_intrinsics.diff

            # ICU now requires C++11
            # see https://trac.macports.org/ticket/59434
            patchfiles-append patch-qtbase-icu_test.diff

            #-----------------------------------------------------------------------------
            # qtbase is used for:
            #    1) building qtbase
            #    2) building MacPorts projects via qmake
            #    3) building end-user projects
            #
            # 1 & 2 require consistency with the MacPorts environment
            # 3 requires consistency with the default Qt installation
            #
            # 2 can be achieved via environment variables
            #    (e.g. QMAKE_MACOSX_DEPLOYMENT_TARGET=${macosx_deployment_target})
            #
            # the only way 3 can be achieved is if no changes are made to the build system
            #
            # the following is an attempt to achieve 1 without destroying 3
            #-----------------------------------------------------------------------------

            # save default spec files
            post-extract {
                copy ${worksrcpath}/mkspecs ${worksrcpath}/mkspecs-save
            }

            # respect MacPorts build variables
            patchfiles-append patch-mkspecs.diff

            # respect configure.compiler
            if { ${configure.compiler} eq "clang" } {
                # let xargs find correct compiler (default behaviour)
                post-patch {
                    # let xargs find correct compiler
                    reinplace \
                        "s|__MACPORTS_CC__|clang|g" \
                        ${worksrcpath}/mkspecs/common/clang.conf

                    reinplace \
                        "s|__MACPORTS_CXX__|clang++|g" \
                        ${worksrcpath}/mkspecs/common/clang.conf
                }
            } else {
                post-patch {
                    reinplace \
                        "s|__MACPORTS_CC__|${configure.cc}|g" \
                        ${worksrcpath}/mkspecs/common/clang.conf

                    reinplace \
                        "s|__MACPORTS_CXX__|${configure.cxx}|g" \
                        ${worksrcpath}/mkspecs/common/clang.conf
                }
            }

            if { [string match macports-clang-* ${configure.compiler}] && [vercmp ${xcodeversion} "7.0"] >= 0 } {
                # non-Xcode clang does not seem to be able to understand tbd files
                # for an explanation of tbd files, see
                #    https://stackoverflow.com/questions/31450690/why-xcode-7-shows-tbd-instead-of-dylib
                # see https://trac.macports.org/ticket/53151
                pre-fetch {
                    ui_error "This configuration is known to fail"
                    ui_error "See https://trac.macports.org/ticket/53151"
                    ui_error "As a workaround, do not set configure.compiler manually"
                    return -code error "incompatible configuration"
                }
            }

            post-patch {

                if {${configure.cxx_stdlib} eq "macports-libstdc++" && ${os.platform} eq "darwin" && ${os.major} < 13} {
                    set cxx_abi " -D_GLIBCXX_USE_CXX11_ABI=0"
                } else {
                    set cxx_abi ""
                }

                # respect configure.cxx_stdlib
                reinplace \
                    "s|__MACPORTS_CXX_STDLIB__|${configure.cxx_stdlib}${cxx_abi}|g" \
                    ${worksrcpath}/mkspecs/common/clang-mac.conf

                # respect macosx_deployment_target
                foreach spec {macx-clang macx-clang-32 macx-g++ macx-g++-32 macx-g++40 macx-g++42 macx-icc macx-llvm} {
                    reinplace \
                        "s|__MACPORTS_DEPLOYMENT_TARGET__|${macosx_deployment_target}|g" \
                        ${worksrcpath}/mkspecs/${spec}/qmake.conf
                }

                #respect configure.optflags
                reinplace \
                    "s|__MACPORTS_OPTFLAGS__|${configure.optflags}|g" \
                    ${worksrcpath}/mkspecs/common/gcc-base.conf
            }

            # respect configure.sdk_version
            post-patch {
                reinplace \
                    "s|__MACPORTS_MAC_SDK__|${qt5.mac_sdk}|g" \
                    ${worksrcpath}/mkspecs/common/macx.conf
            }

            # return modified spec files to the default values
            post-build {
                if { [variant_exists universal] && [variant_isset universal] } {
                    foreach arch ${universal_archs_to_use} {
                        foreach conf {clang.conf macx.conf clang-mac.conf gcc-base.conf} {
                            move -force ${worksrcpath}-${arch}/mkspecs-save/common/${conf} ${worksrcpath}-${arch}/mkspecs/common/${conf}
                        }
                        foreach spec {macx-clang macx-clang-32 macx-g++ macx-g++-32 macx-g++40 macx-g++42 macx-icc macx-llvm} {
                            move -force ${worksrcpath}-${arch}/mkspecs-save/${spec}/qmake.conf ${worksrcpath}-${arch}/mkspecs/${spec}/qmake.conf
                        }
                    }
                } else {
                    foreach conf {clang.conf macx.conf clang-mac.conf gcc-base.conf} {
                        move -force ${worksrcpath}/mkspecs-save/common/${conf} ${worksrcpath}/mkspecs/common/${conf}
                    }
                    foreach spec {macx-clang macx-clang-32 macx-g++ macx-g++-32 macx-g++40 macx-g++42 macx-icc macx-llvm} {
                        move -force ${worksrcpath}/mkspecs-save/${spec}/qmake.conf ${worksrcpath}/mkspecs/${spec}/qmake.conf
                    }
                }
            }

            # --prefix is not recognized.
            configure.pre_args-delete       --prefix=${prefix}

            # --disable-dependency-tracking is not recognized.
            configure.universal_args-delete --disable-dependency-tracking

            # adapted from phantomjs build.py
            configure.args-append \
                -shared \
                -opensource \
                -confirm-license \
                -prefix ${qt_dir} \
                -system-zlib \
                -system-libpng \
                -system-libjpeg \
                -system-pcre \
                -nomake examples \
                -nomake tools \
                -nomake tests \
                -no-qml-debug \
                -no-dbus \
                -no-opengl \
                -no-audio-backend \
                -D QT_NO_GRAPHICSVIEW \
                -D QT_NO_GRAPHICSEFFECT \
                -D QT_NO_STYLESHEET \
                -D QT_NO_STYLE_CDE \
                -D QT_NO_STYLE_CLEANLOOKS \
                -D QT_NO_STYLE_MOTIF \
                -D QT_NO_STYLE_PLASTIQUE \
                -D QT_NO_PRINTPREVIEWDIALOG \
                -qpa phantom \
                -openssl \
                -openssl-linked \
                -no-openvg \
                -no-eglfs \
                -no-egl \
                -no-glib \
                -no-gtkstyle \
                -no-cups \
                -no-sm \
                -no-xinerama \
                -no-xkb \
                -no-xcb \
                -no-kms \
                -no-linuxfb \
                -no-directfb \
                -no-mtdev \
                -no-libudev \
                -no-evdev \
                -no-pulseaudio \
                -no-alsa \
                -no-feature-PRINTPREVIEWWIDGET \
                -force-pkg-config \
                -release

            foreach driver { db2 ibase mysql oci odbc psql sqlite sqlite2 tds } {
                configure.args-append -no-sql-${driver}
            }

            if {!${universal_possible} || ![variant_isset universal]} {
                configure.args-append "-platform ${qt_qmake_spec}"
            } else {
                set merger_configure_args(i386)   "-platform ${qt_qmake_spec_32}"
                set merger_configure_args(x86_64) "-platform ${qt_qmake_spec_64}"
            }

            # http://lists.qt-project.org/pipermail/development/2017-January/028392.html
            # Prefer ICU over iconv

            # Additional options:
            configure.args-append  \
                -no-rpath          \
                -verbose           \
                -icu               \
                -fontconfig        \
                -no-gstreamer

            # MacOS/iOS options:
            configure.args-append    \
                -framework

            # do not use ${configure.sdk_version}
            # SDK is recorded in ${qt_mkspecs_dir}/qdevice.pri
            # SDK may then be removed if Xcode is updated
            # see https://trac.macports.org/ticket/54044
            # see https://trac.macports.org/ticket/55195
            configure.args-append \
                -sdk macosx

            # Qt builds part of the system using environment provided by MacPorts.
            # It builds the rest using its own internal environment.
            # For consistency, clear MacPorts environment.
            #configure.cxx_stdlib
            proc portconfigure::should_add_stdlib {} {return no}
            proc portconfigure::should_add_cxx_abi {} {return no}
            compiler.limit_flags yes
            configure.cc_archflags
            configure.cxx_archflags
            configure.objc_archflags
            configure.objcxx_archflags
            configure.ld_archflags
            configure.cppflags
            configure.cflags
            configure.cxxflags
            configure.objcflags
            configure.objcxxflags
            configure.ldflags
            configure.pipe  no
            if {${universal_possible} && [variant_isset universal]} {
                set merger_arch_flag no
            }
            configure.march
            configure.mtune
            configure.universal_ldflags
            configure.universal_cflags
            configure.universal_cxxflags
            configure.universal_cppflags

            # configure script looks for perl but doesn't seem to use it for our configuration

            # configure script uses gawk if it can find it,
            #    so require it for consistency
            depends_build-append port:gawk

            # unless overridden, configure script uses gmake if it can find it
            configure.env-append MAKE=${build.cmd}

            if {${universal_possible} && [variant_isset universal]} {

                post-destroot {
                    # delete preprocessor comments surrounding QT_CPU_FEATURES.i386 and QT_CPU_FEATURES.x86_64
                    reinplace "/^#ifndef.*$/d" ${destroot}${qt_mkspecs_dir}/qmodule.pri
                    reinplace "/^#else.*$/d"   ${destroot}${qt_mkspecs_dir}/qmodule.pri
                    reinplace "/^#endif.*$/d"  ${destroot}${qt_mkspecs_dir}/qmodule.pri
                }

                # The file ${qt_mkspecs_dir}/qconfig.pri is still not properly merged
                # A workaround is to set QT_ARCH and QT_TARGET_ARCH manually (see e.g. the qmake5 PortGroup)
            }

            # Please do not use -I and -L.
            # -I becomes -isystem in the Qt build system, which is checked *after* CPATH.
            compiler.cpath-prepend    ${prefix}/include/openssl-1.0
            compiler.library_path-prepend \
                                      ${prefix}/lib/openssl-1.0

        } else {
            # these subports use qmake
            PortGroup            qmake5 1.0

            # determine which variants are to be turned off
            set request_examples true
            set request_tests    true
            set def_var          ""

            if { [lsearch -exact [lindex ${module_info} 6] "~universal"] != -1 } {
                universal_variant no
            }

            if { [lsearch -exact [lindex ${module_info} 6] "noarch"] != -1 } {
                supported_archs   noarch
                universal_variant no
            }

            if { [lsearch -exact [lindex ${module_info} 6] "~debug"] != -1 } {
                qt5.debug_variant no
            }

            if { [lsearch -exact [lindex ${module_info} 6] "~examples"] != -1 } {
                set request_examples false
            }

            if { [lsearch -exact [lindex ${module_info} 6] "~tests"] != -1 } {
                set request_tests    false
            }

            if { [lsearch -exact [lindex ${module_info} 6] "++examples"] != -1 } {
                set request_examples true
                lappend def_var "+examples"
            }

            if { ${request_examples} } {
                variant examples description {Build examples} {}
            }

            if { ${request_tests} } {
                variant tests description {Enable tests} {}
            }

            if { ${def_var} ne "" } {
                default_variants-append ${def_var}
            }

            # accommodating variant request varies depending on how qtbase was built
            pre-configure {

                # determine if qmake builds examples by default (set via variants)
                if {[active_variants ${name}-qtbase examples ""]} {
                    set base_examples true
                } else {
                    set base_examples false
                }

                # determine if qmake runs tests by default (set via variants)
                if {[active_variants ${name}-qtbase tests ""]} {
                    set base_tests true
                } else {
                    set base_tests false
                }

                # determine if the user wants to build examples
                if { [variant_exists examples] && [variant_isset examples] } {
                    set this_examples true
                } else {
                    set this_examples false
                }

                # determine if the user wants to run tests
                if { [variant_exists tests] && [variant_isset tests] } {
                    set this_tests true
                } else {
                    set this_tests false
                }

                # determine if qmake's default and user requests are compatible; override qmake if necessary
                if { ${this_examples} && !${base_examples}  } {
                    configure.args-append "QT_BUILD_PARTS+=\"examples\""
                }

                if { !${this_examples} && ${base_examples}  } {
                    configure.args-append "QT_BUILD_PARTS-=\"examples\""
                }

                if { ${this_tests} && !${base_tests}  } {
                    configure.args-append "QT_BUILD_PARTS+=\"tests\""
                }

                if { !${this_tests} && ${base_tests}  } {
                    configure.args-append "QT_BUILD_PARTS-=\"tests\""
                }
            }

            ###############################################################################
            # Special Cases
            ###############################################################################

            # special case
            if { ${module} eq "qtwebkit" } {

                platform darwin 11 {
                    known_fail yes
                    pre-fetch {
                        ui_error "${subport} currently does not build on OS X 10.7, see https://trac.macports.org/ticket/64172"
                        return -code error "incompatible OS version"
                    }
                }

                use_xcode yes

                # from phantomjs build.py
                configure.args-append \
                    WEBKIT_CONFIG-=build_webkit2 \
                    WEBKIT_CONFIG-=netscape_plugin_api \
                    WEBKIT_CONFIG-=use_gstreamer \
                    WEBKIT_CONFIG-=use_gstreamer010 \
                    WEBKIT_CONFIG-=use_native_fullscreen_video \
                    WEBKIT_CONFIG-=video \
                    WEBKIT_CONFIG-=web_audio

                # use MacPorts icu
                #
                # qmake uses pkgconfig to look for icu
                # this feature does not work without "CONFIG += link_pkgconfig"
                patchfiles-append patch-icu.diff

                #https://codereview.qt-project.org/#/c/139967/
                #https://codereview.qt-project.org/#/c/139968/
                #https://codereview.qt-project.org/#/c/139970/
                patchfiles-append patch-ssl.diff

                # qtwebkit uses
                #    glx
                #    libXcomposite
                #    libXrender
                #    if they can be found
                # Ensure that test fails even if software is installed
                post-patch {
                    foreach test { glx libXcomposite libXrender } {
                        reinplace "s|return 0;|return 0;\\\n#error turn off test|g" ${worksrcpath}/Tools/qmake/config.tests/${test}/${test}.cpp
                    }
                }

                # by default, qmake uses -mmacosx-version-min=10.6, which means __MAC_OS_X_VERSION_MIN_REQUIRED is set to 1006
                # setting QMAKE_MACOSX_DEPLOYMENT_TARGET to ${macosx_deployment_target} changes __MAC_OS_X_VERSION_MIN_REQUIRED
                #    and unwanted code is included
                # this patch allows qtwebkit to build, but other problems may crop up
                patchfiles-append patch-deployment_target.diff

                # see https://bugs.webkit.org/show_bug.cgi?id=171612
                patchfiles-append patch-qtwebkit_fix_icu.diff

                # for the PhantomJS version of Qt Webkit, certain symbols need to be global
                patchfiles-append patch-export_global.diff

                # backport upstream WebKit changes to avoid
                # error: "Unsupported PAGE_SHIFT amount"
                # see https://trac.macports.org/ticket/62027#comment:49
                patchfiles-append patch-qtwebkit_fix_page_shift.diff

                # work around https://trac.macports.org/ticket/60975
                patchfiles-append patch-webkit_XPathGrammar.y.diff
                patchfiles-append patch-webkit_makegrammar.pl.diff
            }
        }
    }
}

# see https://doc.qt.io/qt-5/sql-driver.html for info on building SQL Database Drivers
foreach {sql_names sql_info} [array get sql_plugins] {
    set driver          [lindex ${sql_names} 0]
    set dbms            [lindex ${sql_names} 1]
    set revision_string [lindex ${sql_names} 2]
    set revision_string [string range ${revision_string} 1+[string last " " ${revision_string}] end]

    subport ${name}-${driver}-plugin {

        PortGroup qmake5 1.0

        distname        qtbase-opensource-src-${version}

        revision ${revision_string}

        description       ${dbms} Database Driver for Qt Tool Kit ${qt_major}
        long_description  ${dbms} Database Driver for Qt Tool Kit ${qt_major}

        use_xcode yes

        # if there is more than one version of the database system, create variants for each version
        if { [llength ${sql_info}] > 1 } {

            set any_variant_set false

            foreach variant_info ${sql_info} {

                set varName [lindex ${variant_info} 0]

                # find every other variant so it can be marked as conflicting
                set conflicts_list ""
                foreach variant_info2 ${sql_info} {
                    set varName2 [lindex ${variant_info2} 0]

                    if { ${varName} ne ${varName2} } {
                        lappend conflicts_list ${varName2}
                    }
                }

                # get only the numbers from the name
                regexp {[0-9].} ${varName} varVer

                variant ${varName} conflicts ${conflicts_list} description "use version ${varVer} of ${dbms}" {}

                # check if any variant has been set
                if { [variant_isset ${varName}] } {
                    set any_variant_set true
                }
            }

            # ensure at least one variant is set
            if { !${any_variant_set} } {
                default_variants-append +[lindex [lindex ${sql_info} 0] 0]
            }
        }

        foreach variant_info ${sql_info} {
            set varName [lindex ${variant_info} 0]

            if { ( [variant_exists ${varName}] && [variant_isset ${varName}] ) || [llength ${sql_info}]==1 } {
                depends_lib-append [lindex ${variant_info} 1]

                configure.args-append                                    \
                    [subst INCLUDEPATH+=\"[lindex ${variant_info} 2]\"]  \
                    [subst LIBS+=\"[lindex ${variant_info} 3]\"]
            }
        }

        # for single architecture, easier to use
        #    worksrcdir ${worksrcdir}/qtbase/src/plugins/sqldrivers/${driver},
        #    but doesn't work for universal build
        configure.dir ${worksrcpath}/src/plugins/sqldrivers/${driver}
        build.dir     ${configure.dir}
        destroot.dir  ${configure.dir}

        # see https://trac.macports.org/ticket/53248
        qt5.top_level ${worksrcpath}

        # see #52200
        # see https://codereview.qt-project.org/#/c/164673/
        patchfiles-append patch-xcrun.diff
    }
}

if { ${subport} eq ${name} } {
    # the main port is Meta-port to install various modules

    revision            0

    description         Qt Tool Kit ${qt_major}
    long_description    Qt Tool Kit: A cross-platform framework \
        (headers, data, and libraries) for writing \
        cross-platform GUI-based applications.

    master_sites
    distfiles
    use_configure     no
    supported_archs   noarch
    platforms         any
    installs_libs     no

    build {}

    # create a dummy file so the port can be successfully activated
    destroot {
        xinstall -d -m 0755 ${destroot}${prefix}/share/doc/${subport}
        set docfile   [open ${destroot}${prefix}/share/doc/${subport}/README.txt "w"]
        puts ${docfile} "Meta-port for ${name}"
        puts ${docfile} "${long_description}"
        close ${docfile}
    }

    foreach {module module_info} [array get modules] {
        if { [lindex ${module_info} 5] eq "" } {
            depends_run-append port:${name}-${module}
        }
    }

    depends_run-append port:${name}-sqlite-plugin
}

set python_framework ""
set depends_check ""
if { [info exists depends_build] } {
    set depends_check "${depends_check} ${depends_build}"
}
if { [info exists depends_lib] } {
    set depends_check "${depends_check} ${depends_lib}"
}

foreach deps ${depends_check} {
    if { [string first ":python27" ${deps}] >= 0 } {
        # If Qt components use Python, ensure that MacPorts python27 is used
        #
        # a better solution would be to force components to use a specific python program
        # how to accomplish such a thing is not entirely clear
        #
        # see #49838
        #
        # version 5.5.1 (at least) of qtwebengine must find a python version in the interval [2.7, 3)
        #    (see tools/qmake/mkspecs/features/functions.prf)
        # versions 5.5.1 of qtdeclarative and qtwebkit also use python with no way of specifying which one
        #
        set python_framework ${frameworks_dir}/Python.framework/Versions/2.7
    }
}
if { ${python_framework} ne "" } {
    configure.env-append PATH=${python_framework}/bin:$env(PATH)
    build.env-append     PATH=${python_framework}/bin:$env(PATH)
}
unset python_framework

if { ![exists universal_variant] || [option universal_variant] } {
    PortGroup muniversal  1.0
}

if {${universal_possible} && [variant_isset universal]} {

    merger-post-destroot {
        foreach arch ${universal_archs_to_use} {

            set dir ${destroot}-${arch}

            foreach prlfl [glob -nocomplain ${dir}${qt_libs_dir}/*.framework/*.prl] {
                reinplace -q "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${prlfl}
            }

            foreach prlfl [glob -nocomplain ${dir}${qt_libs_dir}/*.prl] {
                reinplace -q "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${prlfl}
            }

            foreach prlfl [glob -nocomplain ${dir}${qt_examples_dir}/widgets/tools/plugandpaint/plugins/*.prl] {
                reinplace -q "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${prlfl}
            }

            if { [file exists ${dir}${qt_libs_dir}/cmake/Qt5Core/Qt5CoreConfigExtrasMkspecDir.cmake] } {
                reinplace "s|macx-clang-32|macx-clang|g" ${dir}${qt_libs_dir}/cmake/Qt5Core/Qt5CoreConfigExtrasMkspecDir.cmake
            }

            # Libs.private contains the value of ${worksrcpath}-${arch}, which prevents merging
            if { [file exists ${dir}${qt_libs_dir}/pkgconfig/Qt5WebKit.pc] } {
                reinplace "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${dir}${qt_libs_dir}/pkgconfig/Qt5WebKit.pc
            }
            if { [file exists ${dir}${qt_libs_dir}/pkgconfig/Qt5WebEngineCore.pc] } {
                reinplace "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${dir}${qt_libs_dir}/pkgconfig/Qt5WebEngineCore.pc
            }

            if { [file exists ${dir}${qt_examples_dir}/declarative/tutorials/gettingStarted/parts/part5/filedialog/Makefile] } {
                reinplace "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${dir}${qt_examples_dir}/declarative/tutorials/gettingStarted/parts/part5/filedialog/Makefile
                reinplace -E "/\\w*-arch \\\\/d"                      ${dir}${qt_examples_dir}/declarative/tutorials/gettingStarted/parts/part5/filedialog/Makefile
                reinplace -E "/\\w*${arch} \\\\/d"                    ${dir}${qt_examples_dir}/declarative/tutorials/gettingStarted/parts/part5/filedialog/Makefile
                reinplace -E {s:-arch +[^ ]+::g}                      ${dir}${qt_examples_dir}/declarative/tutorials/gettingStarted/parts/part5/filedialog/Makefile
                reinplace "s|macx-clang-32|macx-clang|g"              ${dir}${qt_examples_dir}/declarative/tutorials/gettingStarted/parts/part5/filedialog/Makefile
            }

            if { [file exists ${dir}${qt_examples_dir}/multimedia/spectrum/fftreal.framework/fftreal.prl] } {
                reinplace "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${dir}${qt_examples_dir}/multimedia/spectrum/fftreal.framework/fftreal.prl
            }

            if { [file exists ${dir}${qt_examples_dir}/multimedia/spectrum/spectrum.app/Contents/Frameworks/fftreal.framework/fftreal.prl] } {
                reinplace "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${dir}${qt_examples_dir}/multimedia/spectrum/spectrum.app/Contents/Frameworks/fftreal.framework/fftreal.prl
            }

            if { [file exists ${dir}${qt_examples_dir}/sensors/grue/libgruesensor.prl] } {
                reinplace "s|${worksrcpath}-${arch}|${worksrcpath}|g" ${dir}${qt_examples_dir}/sensors/grue/libgruesensor.prl
            }
        }
    }
}

post-destroot {
    # see #44204
    foreach f [glob -nocomplain -tails -directory ${destroot}${qt_libs_dir} *.framework] {
        set framework [file rootname ${f}]

        set include_list   [split ${qt_includes_dir}   '/']
        set framework_list [split ${qt_libs_dir} '/']

        while {[llength ${include_list}] && [llength ${framework_list}]} {
            set var_include   [lindex $include_list   0]
            set var_framework [lindex $framework_list 0]

            if { ${var_include} ne ${var_framework} } {
                break
            }

            # remove first element from list
            set include_list   [lreplace ${include_list} 0 0]
            set framework_list [lreplace ${framework_list} 0 0]
        }

        xinstall -d -m 0755 ${destroot}${qt_includes_dir}
        ln -s [string repeat ../ [llength ${include_list}]][join ${framework_list} /]/${f}/Headers ${destroot}${qt_includes_dir}/${framework}
    }
}

# let phantomjs determine version
livecheck.type      none
