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

name                qt53

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

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

homepage            https://www.qt.io

version             5.3.2

set just_want_qt5_variables yes
PortGroup qt5 1.0
unset just_want_qt5_variables

# 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
PortGroup           cxx11 1.1

master_sites        \
    https://download.qt.io/archive/qt/${branch}/${version}/submodules

# see https://trac.macports.org/ticket/53952
dist_subdir qt5

# file sizes are significantly smaller using xz
if { ${subport} ne ${name} && ${subport} ne "${name}-docs" } {
    use_xz yes
}

conflicts qt3 qt3-mac
# conflict with all other version of qt5
foreach {qt_test_name qt_test_info} [array get available_qt_versions] {
    if {${name} ne ${qt_test_name}} {
        conflicts-append [lindex ${qt_test_info} 0]
    }
}

############################################################################### Modules Not Considered
#
# No qtactiveqt      (Windows Only)
# No qtandroidextras (Android Only)
# No qtwayland       (Linux Only)
# No qtx11extras     (X11 Only)
# No qtwinextras     (Windows Only)
#
###############################################################################

############################################################################### Finding Dependencies
#
# grep -r "%dependencies" *
# find ./ -name sync.profile
#
# grep -r qtCompileTest *
#
# find ./ -name config.tests
#
# find ./ -name Find\*.cmake
#
# grep -r qtHaveModule *
#
# grep -r packagesExist *
#
# port provides `find ./ -name \*.dylib -exec otool -L {} \; | grep /opt/local/libexec/qt5 | cut -d ' ' -f1` | cut -d : -f2 | sort -u
# port provides `find ./ -name \*.dylib -exec otool -L {} \; | grep /opt/local/lib/ | cut -d ' ' -f1` | cut -d : -f2 | sort -u
#
# https://code.qt.io/cgit/qt/qt5.git/tree/.gitmodules?h=5.5.1
#
###############################################################################

############################################################################### Notes
#
# qtconnectivity checks for bluetooth libraries
#    bluez and bluez_le (Linux Only)
#
# qtconnectivity depends on
#    qtandroidextras    (Android Only)
#
# qtserialport depends on
#    ntddmodm           (Windows Only)
#
# qttools depends on
#    qtactiveqt         (Windows Only)
#
# qtwebkit has tests for libraries in:
#     Tools/qmake/mkspecs/features/configure.prf
#     Tools/qmake/config.tests/
#
# the following qt modules found in qt5.5 don't exist in qt5.3 and were removed
# qt3d qtcanvas3d qtwebengine qtwebchannel
#
###############################################################################

############################################################################### 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 http://web.archive.org/web/20160310083902/http://doc.qt.io/archives/qt-5.3/index.html
#
###############################################################################
array set modules {
    qtbase {
        {
            81328db97d97818d780b3910fac7b9c4c7ffc17d
            9a16095ac46dae99d6ddab8bc07065fbe1c36501ed194a3191d07347d7826cb8
            46694044
        }
        ""
        "port:zlib port:libpng port:jpeg path:bin/dbus-daemon:dbus port:tiff port:libmng path:lib/pkgconfig/glib-2.0.pc:glib2 port:icu port:pcre port:harfbuzz"
        ""
        {"Qt Core" "Qt GUI" "Qt Network" "Qt SQL" "Qt Test" "Qt Widgets" "Qt Concurrent" "Qt D-Bus" "Qt OpenGL" "Qt Platform Headers" "Qt Print Support" "Qt XML"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtconnectivity {
        {
            8e8cc8763398d99190bfd53e1cde237f145b1747
            2eb972b85697e9752ed2f2f7e194393650743737a9fe5f48177734c4dbd9096f
            2174252
        }
        ""
        ""
        "qtbase qtdeclarative"
        {"Qt Bluetooth" "Qt NFC"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtenginio {
        {
            3434ab7b2b05a9c9539457e2e3a6d13b13a8cba9
            d5b84656dc6a349db380e42690a18137e562dbaba1930216bb3e3815df6af708
            517552
        }
        ""
        ""
        "qtdeclarative"
        {"Enginio"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtdeclarative {
        {
            01d6f6bd4ceb78efaad8b5d40cb32bba7a80220a
            04108193b9642c0394c157e98b5c1d81f555f9f495289e07ebfb6f03448b2382
            18171760
        }
        "port:python27"
        ""
        "qtbase qtsvg qtxmlpatterns"
        {"Qt QML" "Qt Quick" "Qt Quick Widgets"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtdoc {
        {
            907fc8eefba4e2c836143474f9abd99c0b0bf79f
            9f0daf55a1765f637b5d8096a195842281a49adc5a82e7ddc75e541c62e00f86
            2669772
        }
        ""
        ""
        "qtdeclarative qttools sqlite-plugin"
        {"Qt Reference Documentation"}
        "requires all documentation"
        "variant overrides: ~examples ~tests ~debug noarch ~docs"
        "revision 0"
        "License: "
    }
    qtgraphicaleffects {
        {
            2662247939378db6fc2e92e2ff084bd7b307b9c0
            688f2658a13d2919487d3f5acacb037364ee5c8fe0319f524a7d0a4987ba7ffc
            14326148
        }
        ""
        ""
        "qtdeclarative"
        {"Qt Graphical Effects"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtimageformats {
        {
            34797c23c717dab4c24310cbb43a2bbd2b112e0a
            d303cbceb73774edc0cfdbde6b97b0e41077e242ff6520710890f81bea40e2d4
            2098004
        }
        ""
        "port:jasper port:libmng port:tiff port:webp"
        "qtbase"
        {"Qt Image Formats"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtlocation {
        {
            007259506c28002ce99bfc860c574b9a1ef854cb
            37b4072b531c35389b3acbbbd7259ab6ce4106177b96d67bfe5d3236139814d7
            3304556
        }
        ""
        ""
        "qtbase qtdeclarative qtquickcontrols qtserialport"
        {"Qt Location" "Qt Positioning"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtmacextras {
        {
            ef747701bae101dbc9e8af0c2a576582263ce50d
            8b7e7aeddf301fc547ff9e97e18faa4cc8dfa96872d86ab4f190c5dccc267808
            43312
        }
        ""
        ""
        "qtbase"
        {"Qt Mac Extras"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtmultimedia {
        {
            15bd527f3c70350d44da7376297a6747ea4c210a
            255fac66c93f33743c707da3d41d95c7c562924fe4eb829cbb7b21b2274a0e0b
            3190116
        }
        ""
        ""
        "qtbase qtdeclarative"
        {"Qt Multimedia" "Qt Multimedia Widgets"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtquick1 {
        {
            4cafb260f4fdabf57bb6910e35b4b2f4d693a59b
            9b7b2e895180e4e3e1ed4e7b5ad049b7d021a05c96be6edc5fc433c6de6273fb
            15989460
        }
        ""
        ""
        "qtbase qtscript qtxmlpatterns qtdeclarative qttools qtwebkit"
        {"Qt Declarative"}
        "deprecated"
        "variant overrides: ~docs"
        "revision 0"
        "License: "
    }
    qtquickcontrols {
        {
            f980231e9ce43892ed49b38a0b13ab1f8c429926
            5f890f014d087141b0aaa8954b21b1f85740233b60a556e0e9624227bff6d94e
            857000
        }
        ""
        ""
        "qtdeclarative qtgraphicaleffects"
        {"Qt Quick Controls" "Qt Quick Dialogs" "Qt Quick Layouts" "Qt Quick Extras"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtscript {
        {
            b087e2b0c869440cb1b85930594781a095ea220e
            6e18002c8c993402c7d28b3c0705092e41c18769b6d3ff741e9a3b3ce9d6d7be
            2585704
        }
        ""
        ""
        "qtbase qttools"
        {"Qt Script" "Qt Script Tools"}
        "deprecated in favor QJS* in Qt QML"
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtsensors {
        {
            1013410e49639e8ae650d08f5fd37fc420d38999
            f9359dc42fbd7105eec7a1fb866e90aa772fd694075e5a5691d1a31d08953ae4
            2099272
        }
        ""
        ""
        "qtbase qtdeclarative"
        {"Qt Sensors"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtserialport {
        {
            7bc1ca23bf4751bb2c41fa80db77c8d4f783294d
            a886e0cb08be60e57958676dc91c6f649468184a03c89c2aeabc904d36fd5a4b
            256448
        }
        ""
        ""
        "qtbase"
        {"Qt Serial Port"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtsvg {
        {
            21a0c62ad6fa71234373f6b0e148e80a7f01f815
            1ec5c2f307ee55740cc8c82dc2ca4037dbc0ca398b4e32abbd967535e71ae30f
            1763380
        }
        ""
        ""
        "qtbase"
        {"Qt SVG"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qttools {
        {
            9ec38623a267655a78daaac9493fb6d80549d954
            5d39cdc63d43ae1f954517e517d9a5c24f2b2c91e22dab3ae6b5b81deb49983e
            8993140
        }
        ""
        ""
        "qtbase qtdeclarative"
        {"Qt Designer" "Qt Help" "Qt UI Tools"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qttranslations {
        {
            1097c8b123b8f86c9dc092a4354fc573785fba7d
            29b648f005e9e588714c8e3c2115db65c7a944a6ba84baafb84091d73213c5cd
            1047568
        }
        ""
        ""
        "qttools"
        {"translation files"}
        ""
        "variant overrides: ~examples ~tests ~debug noarch ~docs"
        "revision 0"
        "License: "
    }
    qtwebkit {
        {
            a8c9ee00d63373c53e07782163f5a2c4fff2e903
            e47122ed15e8e1cc32e11b3cd89bacc056437215134a204899f2fddb4fd92e5b
            33445540
        }
        "port:python27"
        "port:fontconfig port:icu port:leveldb port:webp port:libxml2 port:libxslt port:zlib port:sqlite3"
        "qtbase qtdeclarative qtlocation qtmultimedia qtsensors qtxmlpatterns"
        {"Qt WebKit" "Qt WebKit Widgets"}
        "community support only (use Qt WebEngine)"
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtwebkit-examples {
        {
            31ec2b5d55bb70452c4ba9061c0a6f0fed84b2d2
            c8081a0863b7d8e2e39ec0e2fe288331ddab093a682959ba7378392512296482
            3409140
        }
        ""
        ""
        "qtbase qtwebkit qtscript qtsvg qtxmlpatterns qtdeclarative qttools"
        {"examples for Qt WebKit"}
        "deprecated in favor of Qt WebEngine; doen't provide functionality"
        "variant overrides: ++examples ~docs"
        "revision 0"
        "License: "
    }
    qtwebsockets {
        {
            b3c4de693a52a3d6fb02781b95a973cd3ca3b19a
            60533d413b0fa27b1e08642ae77bcaa76a845fa39ddc3d49af573a77e73a38c2
            68888
        }
        ""
        ""
        "qtbase qtdeclarative"
        {"Qt WebSockets"}
        ""
        "variant overrides: "
        "revision 0"
        "License: "
    }
    qtxmlpatterns {
        {
            cec513aa5b925a6d9d05cce3158fc0c16b3f59ee
            acab0307039e117475caf2c95e425ead09ab5ee08ce15205fb3c0af7d7ec1abb
            1314016
        }
        ""
        ""
        "qtbase"
        {"Qt XML Patterns"}
        ""
        "variant overrides: "
        "revision 0"
        "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"
            ""
        }
    }
    {psql PostgreSQL "revision 0"} {
        {
            "postgresql96"
            "port:postgresql96"
            "${prefix}/include/postgresql96"
            "-L${prefix}/lib/postgresql96 -lpq"
            ""
        }
        {
            "postgresql95"
            "port:postgresql95"
            "${prefix}/include/postgresql95"
            "-L${prefix}/lib/postgresql95 -lpq"
            ""
        }
        {
            "postgresql94"
            "port:postgresql94"
            "${prefix}/include/postgresql94"
            "-L${prefix}/lib/postgresql94 -lpq"
            ""
        }
        {
            "postgresql84"
            "port:postgresql84"
            "${prefix}/include/postgresql84"
            "-L${prefix}/lib/postgresql84 -lpq"
            ""
        }
    }
    {mysql MySQL "revision 0"} {
        {
            "mariadb55"
            "port:mariadb"
            "${prefix}/include/mariadb/mysql"
            "-L${prefix}/lib/mariadb/mysql -lmysqlclient_r"
            ""
        }
        {
            "mysql57"
            "port:mysql57"
            "${prefix}/include/mysql57/mysql"
            "-L${prefix}/lib/mysql57/mysql -lmysqlclient_r"
            ""
        }
        {
            "mysql56"
            "port:mysql56"
            "${prefix}/include/mysql56/mysql"
            "-L${prefix}/lib/mysql56/mysql -lmysqlclient_r"
            ""
        }
    }
}

# 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 5.3 has not been built or tested on 10.5 or less at present on MacPorts
if { ${os.major} < 10 } {
    pre-fetch {
        ui_error "${subport} requires OS X 10.6 or later"
        return -code error "incompatible OS version"
    }
}

# this block has been disabled so the distfiles will be mirrored. Once they are mirrored, it can be enabled again
# Qt 5.3 has not been built or tested on 10.7 or greater at present on MacPorts
# if { ${os.major} > 10 } {
#    pre-fetch {
#        ui_error "${subport} has not been tested on OS X 10.7 or later"
#        ui_error "You likely would prefer to use the default qt5 version for your system."
#        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}

        if { ${revision_string} ne "0" } {
            revision ${revision_string}
        }

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

        checksums                                        \
            rmd160  [lindex [lindex ${module_info} 0] 0] \
            sha256  [lindex [lindex ${module_info} 0] 1] \
            size    [lindex [lindex ${module_info} 0] 2]

        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 { [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"
                    }
                }
            }

            # Qt uses TLS protocols introduced in OS X 10.8
            # see https://developer.apple.com/reference/security/sslprotocol/ktlsprotocol11
            # see https://developer.apple.com/reference/security/sslprotocol?language=objc
            pre-fetch {
                if { ${os.major} < 12 && ![variant_isset openssl] } {
                    ui_error "using Secure Transport requires OS X 10.8 or later"
                    ui_error "please use openssl variant"
                    return -code error "incompatible variant choice"
                }
            }

            # 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"
            # this qt55 patch does not apply on qt53 and link issue does not occur
            # 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/
            # this qt55 patch does not apply on qt53 and does not appear to be needed
            # patchfiles-append patch-stdloc.diff

            #https://codereview.qt-project.org/#/c/138349
            # this qt55 patch has been modified for qt53
            patchfiles-append patch-rpath.diff

            # as of 5.6.1, avoid "... is lacking an install target"
            # see https://codereview.qt-project.org/#/c/156610/1
            patchfiles-append patch-install_examples.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.
            # this qt55 patch does not apply on qt53 and does not appear to be needed
            # 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 xcrun --find Rez]|g" \
                    mkspecs/common/mac.conf \
                    mkspecs/features/mac/rez.prf
            }
            
            # new qt53 patch - don't force deployment target to 10.7 for c++11
            patchfiles-append patch-allow-c++11-with-106OSDK.diff
            
                        
            # in /Developer/SDKs/MacOSX10.6.sdk/usr/include/rpcsvc/yp_prot.h we have the following block,
            # but c++11 already defines bool, so an error occurs 

#           #ifndef BOOL_DEFINED
#           typedef unsigned int bool;
#           #define BOOL_DEFINED
#           #endif

            # defining BOOL_DEFINED for the nis test fixes this for qtbase build. May need it later
            # and if so will have to add it to the qmake5 PG
            patchfiles-append patch-qt53-SL-nispro.diff

            # https://github.com/qt/qtbase/commit/cf63c63d558227fdbef09699c261560e7474f5ea
            # new patch for qt53. This fix was added to later qt5 mainline.
            patchfiles-append patch-fix-nullable-clang.diff

            # new patch for qt53
            # xcrun on 10.6 works differently than on 10.7+. It does not accept a full pathspec to a tool.
            # so we instead have to disable adding the SDK tool prefix in configure to allow MacPorts-installed compilers to be used
            patchfiles-append patch-qt53-disable-macsdkify.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
            # this qt55 patch has been modified for qt53 to spec AR and RANLIB
            # it requires cctools to be installed
            depends_build-append port:cctools
            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
                    reinplace \
                        "s|@@PREFIX@@|${prefix}|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
                    reinplace \
                        "s|@@PREFIX@@|${prefix}|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.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
            }

            if { [vercmp ${xcodeversion} "7.0"] >= 0 } {
                # starting with Xcode 7.0, the SDK for build OS version might not be available
                # see https://trac.macports.org/ticket/53597

                set sdks_dir ${developer_dir}/Platforms/MacOSX.platform/Developer/SDKs
                if { ![file exists ${sdks_dir}/MacOSX${configure.sdk_version}.sdk] } {
                    configure.sdk_version
                }
            }

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

            # return modified spec files to the default values, except clang-mac.conf
            # the modified clang-mac.conf was retained here and not overwritten as the mkspecs-save version hard-codes libc++ 
            # we could consider retaining clang.conf here as well, as it adds the AR and RANLIB specs. However, it also adds
            # a hard-coded compiler spec, which is a problem if a different compiler is chosen, so handle the AR and RANLIB
            # in qmake5 1.0 PG instead
            post-build {
                if { [variant_exists universal] && [variant_isset universal] } {
                    foreach arch ${universal_archs_to_use} {
                        foreach conf {clang.conf macx.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 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

            # Installation options:
            #-extprefix     SYSROOT/PREFIX
            #-hostprefix    EXTPREFIX
            #-libexecdir    ARCHDATADIR/libexec
            #-hostbindir    HOSTPREFIX/bin
            #-hostlibdir    HOSTPREFIX/lib
            configure.args-append                      \
                -prefix         ${qt_dir}              \
                -bindir         ${qt_bins_dir}         \
                -headerdir      ${qt_includes_dir}     \
                -libdir         ${qt_libs_dir}         \
                -archdatadir    ${qt_archdata_dir}     \
                -plugindir      ${qt_plugins_dir}      \
                -importdir      ${qt_imports_dir}      \
                -qmldir         ${qt_qml_dir}          \
                -datadir        ${qt_data_dir}         \
                -docdir         ${qt_docs_dir}         \
                -translationdir ${qt_translations_dir} \
                -sysconfdir     ${qt_sysconf_dir}      \
                -examplesdir    ${qt_examples_dir}     \
                -testsdir       ${qt_tests_dir}        \
                -hostdatadir    ${qt_host_data_dir}

            # Configure options:
            configure.args-append \
                -release          \
                -opensource       \
                -confirm-license  \
                -shared           \
                -largefile        \
                -accessibility

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

            if { ![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}"
            }

            configure.args-append \
                -no-testcocoon    \
                -no-gcov          \
                -force-pkg-config

            # turn off CFG_CLOEXEC if gnulib is installed

            # Third Party Libraries:
            configure.args-append   \
                -system-zlib        \
                -no-mtdev           \
                -no-journald        \
                -system-libpng      \
                -system-libjpeg     \
                -no-freetype        \
                -system-harfbuzz    \
                -no-openssl         \
                -system-pcre        \
                --disable-xcb       \
                -no-xinput2         \
                -no-xcb-xlib        \
                -glib               \
                -no-pulseaudio      \
                -no-alsa            \
                -no-gtkstyle

            # these configure args from qt55 were not accepted by qt53
            #  -no-libproxy        \
            #  -no-xkbcommon-evdev \
            #  -no-xkbcommon-x11   \

            # from the configure script:
            #     NOTE: -optimized-tools is not useful in -release mode.

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

            # Additional options:
            configure.args-append       \
                {-make libs}            \
                {-make tools}           \
                {-nomake examples}      \
                {-nomake tests}         \
                -gui                    \
                -widgets                \
                -no-rpath               \
                -verbose                \
                -nis                    \
                -cups                   \
                -no-iconv               \
                -no-evdev               \
                -no-tslib               \
                -icu                    \
                -no-fontconfig          \
                -strip                  \
                -no-pch                 \
                -dbus-linked            \
                -no-separate-debug-info \
                -no-xcb                 \
                -no-eglfs               \
                -no-directfb            \
                -no-linuxfb             \
                -no-kms                 \
                -no-system-proxies

            # these configure args from qt55 were not accepted by qt53
            #  -no-use-gold-linker     \
            #  -no-libinput            \
            #  -no-gstreamer           \

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

            # 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

            if { ${os.major} < 11 } {
                # on 10.6.8, build against the 10.6.8 SDK
                configure.args-append -sdk macosx10.6
            } else {
                # untested at present
                configure.args-append -sdk macosx
            }

            # configure options that don't show up in configure --help
            configure.args-append \
                -no-libudev       \
                -no-egl           \
                -no-openvg

            # Qt builds part of the system using environment provided my MacPorts.
            # It builds the rest using its own internal environment.
            # For consistency, clear MacPorts environment.
            #configure.cxx_stdlib
            proc portconfigure::should_add_stdlib {} {return false}
            proc cxx11.add_dependencies {} {}
            configure.sdkroot
            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 { [variant_isset universal] } {
                set merger_arch_flag no
            }
            configure.march
            configure.mtune
            configure.universal_ldflags
            configure.universal_cflags
            configure.universal_cxxflags
            configure.universal_cppflags

            # cofigure 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 { [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)
            }

            variant tests description {Enable tests} {
                configure.args-replace {-nomake tests} {-make tests}
            }

            variant examples description {Build examples} {
                configure.args-replace {-nomake examples} {-make examples}
            }

            variant debug description {Build both release and debug libraries} {
                configure.args-replace -release -debug-and-release
            }

            variant pulseaudio description {Compile PulseAudio support} {
                depends_lib-append port:pulseaudio
                configure.args-replace -no-pulseaudio -pulseaudio
            }

            variant gstreamer description {Compile GStreamer support} {
                depends_lib-append port:gstreamer1 port:gstreamer1-gst-plugins-base
                configure.args-replace -no-gstreamer {-gstreamer 1.0}
            }

            variant openssl description {Use OpenSSL instead of Secure Transport} {
                configure.args-delete -securetransport -no-openssl
                configure.args-append -openssl-linked

                # see https://trac.macports.org/ticket/58204
                depends_lib-append    port:openssl10
                configure.args-append -I${prefix}/include/openssl-1.0 \
                                      -L${prefix}/lib/openssl-1.0
            }
            default_variants-append +openssl

        } else {
            # these subports use qmake
            PortGroup            qmake5 1.0

            # detremint 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 varians)
                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 of 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 "qtdoc" } {
                build.target    docs
                destroot.target install_docs

                # in the process of building the html files, qtdoc looks for all installed modules
                #    with no clear way to select only a subset
                # unless a way is found, ReproducibleBuilds (https://trac.macports.org/wiki/ReproducibleBuilds)
                #    requires qtdoc depend on all the documentation modules
                foreach {module_doc module_doc_info} [array get modules] {
                    if { [lsearch -exact [lindex ${module_doc_info} 6] "~docs"] == -1 } {
                        if { ${os.major} >= 12 || (${module_doc} ne "qtwebengine") } {
                            depends_lib-append port:${name}-${module_doc}-docs
                        }
                    }
                }
            }

            # special case
            if { ${module} eq "qtlocation" } {
                # qtlocation uses
                #    Gypsy (https://gypsy.freedesktop.org/wiki/)
                #    if they can be found
                # Ensure that test fails even if software is installed
                post-patch {
                    foreach test { gypsy } {
                        reinplace "s|return 0;|return 0;\\\n#error turn off test|g" ${worksrcpath}/config.tests/${test}/main.cpp
                    }
                }
            }

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

                # use MacPorts icu
                #
                # qmake uses pkgconfig to look for icu
                # this feature does not work without "CONFIG += link_pkgconfig"
                # qt55 patch modified for qt53. One chunk of the old patch did not apply, and doesn't seem needed any longer
                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

                # new patch for qt53 -- there is a minor bug in the include define logic in one file
                patchfiles-append patch-qt53-qtwebkit-unistd-include.diff
            }

            # special case
            if { ${module} eq "qttools" } {
                # prevent qttools from opportunistically using qtwebkit if it can be found
                # this qt55 patch was modified for qt53
                patchfiles-append patch-no_qtwebkit.diff

                variant qtwebkit description {build with QtWebkit support} {
                    patchfiles-delete patch-no_qtwebkit.diff
                    depends_lib-append port:${name}-qtwebkit
                }

                post-extract {
                    # these folders are installed and conflict with ${name}-qttools-docs
                    delete ${worksrcpath}/examples/assistant/simpletextviewer/documentation
                    delete ${worksrcpath}/examples/help/contextsensitivehelp/docs
                }

                # see #44934 (and #35067 for the qt4-mac version)
                set framework_list [split ${qt_frameworks_dir} '/']
                set qt_list        [split ${qt_dir} '/']

                while {[llength ${qt_list}] && [llength ${framework_list}]} {
                    set var_qt        [lindex $qt_list        0]
                    set var_framework [lindex $framework_list 0]

                    if { ${var_qt} ne ${var_framework} } {
                        break
                    }

                    # remove first element from list
                    set qt_list        [lreplace ${qt_list}        0 0]
                    set framework_list [lreplace ${framework_list} 0 0]
                }
                set libreplace [string repeat ../ [llength ${qt_list}]][join ${framework_list} /]
                if { ${libreplace} ne "lib" } {
                    patchfiles-append patch-shared.diff
                    post-patch {
                        reinplace "s|__MACPORTS_FRAMWORK_DIR__|${libreplace}|g" ${worksrcpath}/src/macdeployqt/shared/shared.cpp
                    }
                }
            }

            # special case
            if { ${module} eq "qtsensors" && [variant_isset examples] } {
                if { [variant_isset debug] } {
                    set debug "_debug"
                } else {
                    set debug ""
                }
                # fix library path names or MacPorts will try to reinstall
                post-destroot {
                    foreach dylib "grue/Grue/libdeclarative_grue${debug}.dylib grue/libgruesensor.1.dylib grue/sensors/libqtsensors_grue${debug}.dylib sensor_explorer/Explorer/libdeclarative_explorer${debug}.dylib" {
                        system "/usr/bin/install_name_tool -id ${qt_examples_dir}/sensors/${dylib} ${destroot}${qt_examples_dir}/sensors/${dylib}"
                    }
                    foreach dylib "grue/Grue/libdeclarative_grue${debug}.dylib grue/sensors/libqtsensors_grue${debug}.dylib" {
                        system "/usr/bin/install_name_tool -change libgruesensor.1.dylib ${qt_examples_dir}/sensors/grue/libgruesensor.1.dylib ${destroot}${qt_examples_dir}/sensors/${dylib}"
                    }
                }
            }

            # special case
            if { ${module} eq "qtconnectivity" } {
                # several patches were added to later versions of qt-qtconnectivity to allow them
                # to build with newer SDKs - none of these patches apply on qt53 "as is" and 
                # none of them are relevant to systems < 10.12 it appears -- just ignore them
                # TODO: this entire block and ass't patches can be removed after suitable review

                # https://codereview.qt-project.org/#/c/172619/
                # patchfiles-append patch-qtconn-for-10.12.diff

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

                # @property UUID was removed in SDK 10.13
                # avoid osx/osxbtcentralmanager.mm:241:34: error: call to implicitly-deleted copy constructor of 'ObjCScopedPointer<NSMutableArray>'
                # @property isConnected was removed in SDK 10.13
                # patchfiles-append patch-qtconnectivity-uuid.diff
            }

            # special case
            if { ${module} eq "qtwebkit-examples" && ![variant_isset examples] } {
                # create a dummy file so the port can be successfully activated
                post-destroot {
                    xinstall -d -m 0755 ${destroot}${prefix}/share/doc/${subport}
                    set docfile [open ${destroot}${prefix}/share/doc/${subport}/README.txt "w"]
                    puts ${docfile} "Without the examples variant, no examples are installed"
                    puts ${docfile} "${long_description}"
                    close ${docfile}
                }
            }

            # special case
            if { ${module} eq "qtscript" } {
                # see https://trac.macports.org/ticket/54453
                patchfiles-append patch-qtscript_ceil.diff
            }
        }
    }

    if { [lsearch -exact [lindex ${module_info} 6] "~docs"] == -1 } {

        subport ${name}-${module}-docs {

            supported_archs   noarch
            installs_libs     no
            universal_variant no

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

            if { ${revision_string} ne "0" } {
                revision ${revision_string}
            }

            description       Documentation for the port ${name}-${module}
            long_description  ${description}

            build.target    docs
            destroot.target install_docs

            checksums                                        \
                rmd160  [lindex [lindex ${module_info} 0] 0] \
                sha256  [lindex [lindex ${module_info} 0] 1] \
                size    [lindex [lindex ${module_info} 0] 2]

            depends_build-append            \
                port:${name}-qttools        \
                port:${name}-sqlite-plugin

            # depend on the modules for which this subport provides documentation
            # also have the same build dependencies
            depends_build-append port:${name}-${module}
            foreach deps [lindex ${module_info} 1] {
                depends_build-append [subst ${deps}]
            }

            PortGroup           qmake5 1.0

            qt5.debug_variant   no

            # special cases
            if { ${module} eq "qttools" || ${module} eq "qtbase" } {
                post-extract {
                    # generated makefiles assume full Qt was built locally
                    xinstall -d -m 0755             ${worksrcpath}/bin/
                    foreach bin {qdoc qhelpgenerator} {
                        ln -s ${qt_bins_dir}/${bin} ${worksrcpath}/bin/
                    }

                    xinstall -d -m 0755 ${worksrcpath}/lib/QtHelp.framework/Headers/QtHelp
                    ln -s \
                        ${qt_libs_dir}/QtHelp.framework/Versions/5/Headers/QHelpEngineCore \
                        ${worksrcpath}/lib/QtHelp.framework/Headers/QtHelp

                    ln -s \
                        ${qt_libs_dir}/QtHelp.framework/Versions/5/Headers/qhelpenginecore.h \
                        ${worksrcpath}/lib/QtHelp.framework/Headers

                    ln -s \
                        ${qt_libs_dir}/QtHelp.framework/Versions/5/Headers/qhelp_global.h \
                        ${worksrcpath}/lib/QtHelp.framework/Headers/QtHelp

                }
            } elseif { ${module} eq "qtwebkit" } {
                post-extract {
                    # without this file, the makefile ${worksrcpath}/qtwebkit/Source/WebCore/Makefile.WebCore.Target
                    #    keeps generating itself over and over again
                    # this file is only created when the library is being built, however
                    xinstall -d -m 0755 ${worksrcpath}/Source/WebCore/generated
                    touch ${worksrcpath}/Source/WebCore/generated/InspectorBackendCommands.qrc
                }
            }
        }
    }
}

# 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}

        if { ${revision_string} ne "0" } {
            revision ${revision_string}
        }

        checksums                                          \
            rmd160  [lindex [lindex $modules(qtbase) 0] 0] \
            sha256  [lindex [lindex $modules(qtbase) 0] 1] \
            size    [lindex [lindex $modules(qtbase) 0] 2]

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

        # 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
    }
}

subport ${name}-docs {
    # meta-port to install documentation for various modules

    #revision 0

    description         Documentation for Qt Tool Kit ${qt_major}
    long_description    Documentation for Qt Tool Kit ${qt_major}

    master_sites
    distfiles
    use_configure     no
    supported_archs   noarch
    installs_libs     no
    universal_variant 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 "" } {
            if { [lsearch -exact [lindex ${module_info} 6] "~docs"] == -1 } {
                depends_run-append port:${name}-${module}-docs
            }
        }
    }
}

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
    installs_libs     no
    universal_variant 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 { [variant_exists universal] && [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}
    }

    # .app and non-.app programs are both put in qt_bins_dir
    # put a link of any .app programs in the ${qt_apps_dir}
    if { ${qt_bins_dir} ne ${qt_apps_dir} } {
        xinstall -d -m 0755 ${destroot}${qt_apps_dir}
        foreach app [glob -nocomplain -tails -directory ${destroot}${qt_bins_dir} *.app] {
            ln -s ${qt_bins_dir}/${app} ${destroot}${qt_apps_dir}
        }
    }

    # put configuration files in places they will be found automatically
    if { ${qt_libs_dir} ne "${prefix}/lib" } {

        # put link to pkgconfig files in place where pkgconfig will find it
        # most Qt 5 pkgconfig files begin with Qt5, so link should not conflict with any other Qt installations
        #    exceptions: Enginio (new in Qt 5.3, removed in Qt 5.7)
        xinstall -d -m 0755 ${destroot}${prefix}/lib/pkgconfig
        foreach pcfile [glob -nocomplain -tails -directory ${destroot}${qt_libs_dir}/pkgconfig *.pc] {
            ln -s ${qt_libs_dir}/pkgconfig/${pcfile} ${destroot}${prefix}/lib/pkgconfig
        }

        # put link to cmake files in place where cmake will find it
        # most Qt 5 cmake directories begin with Qt5, so link should not conflict with any other Qt installations
        #    exceptions: Enginio (new in Qt 5.3, removed in Qt 5.7)
        xinstall -d -m 0755 ${destroot}${prefix}/lib/cmake
        foreach cmakedir [glob -type d -nocomplain -tails -directory ${destroot}${qt_libs_dir}/cmake *] {
            xinstall -d -m 0755 ${destroot}${prefix}/lib/cmake/${cmakedir}
            foreach cmakefile [glob -tails -directory ${destroot}${qt_libs_dir}/cmake/${cmakedir} *.cmake] {
                ln -s ${qt_libs_dir}/cmake/${cmakedir}/${cmakefile} ${destroot}${prefix}/lib/cmake/${cmakedir}/
            }
        }

        # if cmake finds configuration files in ${prefix}/lib/cmake, CMAKE_CURRENT_LIST_DIR expands to ${prefix}/lib/cmake/xxx
        # cmake configuration files actually installed in ${qt_cmake_module_dir}/xxx
        foreach cmakedir [glob -type d -nocomplain -tails -directory ${destroot}${qt_libs_dir}/cmake *] {
            foreach cmakefile [glob -nocomplain -directory ${destroot}${qt_libs_dir}/cmake/${cmakedir} *.cmake] {
                reinplace -q "s|\\\${CMAKE_CURRENT_LIST_DIR}|${qt_cmake_module_dir}/${cmakedir}|g" ${cmakefile}
            }
        }
    }
}

if {${subport} eq ${name}} {
    livecheck.type      regex
    livecheck.url       https://download.qt.io/archive/qt/${branch}/
    livecheck.regex     (\\d+(\\.\\d+)+)
} else {
    livecheck.type      none
}
