# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:filetype=tcl:et:sw=4:ts=4:sts=4
# $Id: Portfile 119923 2014-05-10 14:14:24Z mcalhoun@macports.org $

PortSystem      1.0
PortGroup       muniversal 1.0

name            dbus
conflicts       dbus-devel
version         1.8.2
maintainers     mcalhoun openmaintainer
categories      devel
platforms       darwin
license         {AFL-2.1 GPL-2+}
description     A message bus system, a simple way for applications to talk to one another.

long_description \
    ${description}

homepage        http://www.freedesktop.org/Software/dbus
master_sites    http://dbus.freedesktop.org/releases/dbus

checksums           rmd160  5ca50a12dd5bbdab55ed83a1a0eba3535d1e810a \
                    sha256  5689f7411165adc953f37974e276a3028db94447c76e8dd92efe910c6d3bae08

# See r59386
# See r68276
patchfiles      patch-bus-system.conf.in.diff \
                patch-dbus-dbus-sysdeps-unix.c.diff

# See #43203
if { ${os.major} < 11 } {
    patchfiles-append patch-bus-dir-watch-kqueue.c.diff
}

depends_build       \
    port:pkgconfig

unset -nocomplain startup_root
if { [variant_isset no_root] } {
    set dbus_user     ${install.user}
    set dbus_group    ${install.group}
    
    # look for place to install startup files
    if { [tbool startupitem.install] } {
        # See #28121 and #42994
        #set startup_root  [join [lrange [exec /usr/bin/dscl . -read Users/${install.user} NFSHomeDirectory] 1 end]]
        #set startup_root  [join [lrange [exec /usr/bin/dscl '/Active Directory/All Domains' -read Users/${install.user} NFSHomeDirectory] 1 end]]
        foreach datasource [list . "'/Active Directory/All Domains'" ] {
            if { ! [catch {system "/usr/bin/dscl ${datasource} -read Users/${install.user} NFSHomeDirectory"}] } {
                ui_debug "dscl found ${install.user} in ${datasource}"
                set startup_root [join [lrange [exec /usr/bin/dscl ${datasource} -read Users/${install.user} NFSHomeDirectory] 1 end]]
                break
            } else {
                ui_debug "dscl can not find ${install.user} in ${datasource}"
            }
        }
        if { ! [info exists startup_root] } {
            if { ![tbool startupitem.install] } {
                ui_debug "Unable to find a valid home directory, but user disallows startup items."
            } else {
                ui_warn "Unable to find a valid home directory even though user requested startup items be installed."
            }        
        }
    }
} else {
    if { [variant_isset underscore] } {
        set dbus_user     _messagebus
    } else {
        set dbus_user     messagebus
    }
    set dbus_group    ${dbus_user}
    
    if { [tbool startupitem.install] } {
        set startup_root  ""
    }
}
add_users         ${dbus_user} group=${dbus_group} realname=Message\ Bus

depends_lib     port:expat

configure.args  --disable-doxygen-docs \
                --disable-xml-docs \
                --without-x \
                --enable-launchd \
                --with-launchd-agent-dir=${prefix}/Library/LaunchAgents \
                --with-dbus-user=${dbus_user} \
                --disable-tests

set sudo ""
if {![variant_isset no_root]} {
    set sudo "sudo "
}

# These variants are obsolete
# dbus should respect the global variable startupitem.install set in ${prefix}/etc/macports/macports.conf
# See https://guide.macports.org/#reference.startupitems
if { [variant_isset startupitem] } {
    pre-configure {
        if { ![tbool startupitem.install] } {
            ui_error "You have requested an obsolete variant that conflicts with the value of startupitem.install set in ${prefix}/etc/macports/macports.conf"
            ui_error "If you want to install the startup items, please change the global variable in ${prefix}/etc/macports/macports.conf"
            ui_error "Note: this will affect other ports"
            ui_error "See https://guide.macports.org/#reference.startupitems"
            return -code error "invalid obsolete variant"
        } else {
            ui_warn "You have requested an obsolete variant"
            ui_warn "Installation of startup items are now determined by ${prefix}/etc/macports/macports.conf"
            ui_warn "See https://guide.macports.org/#reference.startupitems"
        }
    }
}

if { [variant_isset no_startupitem] } {
    pre-configure {
        if { [tbool startupitem.install] } {
            ui_error "You have requested an obsolete variant that conflicts with the value of startupitem.install set in ${prefix}/etc/macports/macports.conf"
            ui_error "If you do not want to install the startup items, please change the global variable in ${prefix}/etc/macports/macports.conf"
            ui_error "Note: this will affect other ports"
            ui_error "See https://guide.macports.org/#reference.startupitems"
            return -code error "invalid obsolete variant"            
        } else {
            ui_warn "You have requested an obsolete variant"
            ui_warn "Installation of startup items are now determined by ${prefix}/etc/macports/macports.conf"
            ui_warn "See https://guide.macports.org/#reference.startupitems"
        }
    }
}

post-patch {
    reinplace "s|/usr/local|${prefix}|g" ${worksrcpath}/dbus/dbus-sysdeps-unix.c
    reinplace {s|broken_poll="no (cross compiling)"|broken_poll=yes|} ${worksrcpath}/configure
    
    if { [tbool startupitem.create] } {
        # Disable if installed into startup directory.
        reinplace "s|</array>|</array>\\\n\\\n\\\t<key>Disabled</key>\\\n\\\t<true/>|" \
            ${worksrcpath}/bus/org.freedesktop.dbus-session.plist.in
    }
}

use_parallel_build  yes

test.run        yes
test.target     check

pre-test {
    if {![variant_isset test]} {
        ui_error "test variant must be activated to enable test support."
        error "Please enable test variant."
    }
}

destroot.keepdirs \
    ${destroot}${prefix}/share/dbus-1/services \
    ${destroot}${prefix}/var/run/dbus \
    ${destroot}${prefix}/etc/dbus-1/system.d \
    ${destroot}${prefix}/etc/dbus-1/session.d

set plistDir  ${prefix}/Library/LaunchDaemons
set plistFl   ${plistDir}/org.freedesktop.dbus-system.plist

set labelDaemon [file rootname [file tail ${plistFl}]]
set labelAgent [file rootname org.freedesktop.dbus-session.plist]

# universal_archs_to_use might not be set before pre-fetch.
pre-destroot {
    global merger_dont_diff merger_configure_env

    # PortGroup muniversal has difficulty merging three files.
    if {[info exists universal_archs_to_use] && [llength ${universal_archs_to_use}] == 3} {
        set merger_dont_diff "${prefix}/lib/dbus-1.0/include/dbus/dbus-arch-deps.h"
    }
}

post-destroot {
    # Simplify startup script over startupitem.install.
    # See #15081
    xinstall -d -m 0755 ${destroot}${plistDir}
    set plist [open "${destroot}${plistFl}" w 0644]
    
    puts ${plist} "<?xml version='1.0' encoding='UTF-8'?>"
    puts ${plist} "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\""
    puts ${plist} "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\" >"
    puts ${plist} "<plist version='1.0'>"
    puts ${plist} "<dict>"
    
    puts ${plist} "<key>Label</key><string>org.freedesktop.dbus-system</string>"
    
    puts ${plist} "<key>ProgramArguments</key>"
    puts ${plist} "<array>"
    puts ${plist} "\t<string>${prefix}/bin/dbus-daemon</string>"
    puts ${plist} "\t<string>--system</string>"
    puts ${plist} "\t<string>--nofork</string>"
    puts ${plist} "</array>"
    if {$macosx_deployment_target eq "10.4"} {
        puts ${plist} "<key>OnDemand</key><false/>"
    } else {
        puts ${plist} "<key>KeepAlive</key><true/>"
    }

    if { [tbool startupitem.install] } {
        puts ${plist} "<key>Disabled</key><true/>"
    }
    
    puts ${plist} "</dict>"
    puts ${plist} "</plist>"
    
    close ${plist}
    
    if { [info exists startup_root] } {
        xinstall -d -m 0755 ${destroot}${startup_root}/Library/LaunchDaemons
        xinstall -d -m 0755 ${destroot}${startup_root}/Library/LaunchAgents
        ln -s ${plistFl} ${destroot}${startup_root}/Library/LaunchDaemons
        ln -s ${prefix}/Library/LaunchAgents/org.freedesktop.dbus-session.plist ${destroot}${startup_root}/Library/LaunchAgents
    }
    
    system "env DYLD_LIBRARY_PATH=${destroot}${prefix}/lib ${destroot}${prefix}/bin/dbus-uuidgen --ensure=${destroot}${prefix}/var/lib/dbus/machine-id"
}

pre-activate {
    if { [file exists ${prefix}/var/lib/dbus/machine-id] } {
        # See #19234
        delete ${prefix}/var/lib/dbus/machine-id
    }
}

post-activate {
    file attributes ${prefix}/var/run/dbus -group ${dbus_group} -owner ${dbus_user}
    file attributes ${prefix}/libexec/dbus-daemon-launch-helper -group ${dbus_group}
    
    if { [tbool startupitem.install] && ![variant_isset no_root] } {
        file attributes ${prefix}/Library/LaunchAgents/org.freedesktop.dbus-session.plist -owner root -group wheel
        file attributes ${prefix}/Library/LaunchDaemons/[file tail ${plistFl}] -owner root -group wheel
    }
}

#pre-deactivate {
#    if { [info exists startup_root] } {
#        catch {system "launchctl unload ${startup_root}/Library/LaunchDaemons/[file tail ${plistFl}]"}
#        catch {system "launchctl unload ${startup_root}/Library/LaunchAgents/org.freedesktop.dbus-session.plist"}
#    }
#}

# XXX Building with tests enabled causes dbus to link with dbus-glib,
# which it shouldn't do because that port depends on this one: see #30088
variant test description {enable tests (Only Works if dbus is Already Installed)} {
    ui_warn "This variant requires circular dependencies and only works if ${name} is already installed"

    configure.args-replace  --disable-tests --enable-tests
    configure.args-append   --without-dbus-glib
    depends_build-append      port:glib2
    depends_build-append      port:python27 port:dbus-python27 port:py27-gobject port:dbus-python
    configure.python        ${prefix}/bin/python2.7
}

if { [info exists startup_root] } {
    notes "############################################################################
# Startup items have been generated that will aid in
# starting ${name} with launchd. They are disabled
# by default. Execute the following commands to start them,
# and to cause them to launch at startup:
#
# ${sudo}launchctl load -w ${startup_root}/Library/LaunchDaemons/[file tail ${plistFl}]
# launchctl load -w ${startup_root}/Library/LaunchAgents/org.freedesktop.dbus-session.plist
############################################################################"
} else {
    notes "############################################################################
# Startup items were not installed for ${name}
# Some programs which depend on ${name} might not function properly.
# To load ${name} manually, run
#
# launchctl load -w ${prefix}/Library/LaunchDaemons/[file tail ${plistFl}]
# launchctl load -w ${prefix}/Library/LaunchAgents/org.freedesktop.dbus-session.plist
############################################################################"
}

variant no_root conflicts underscore description {Run the DBUS daemon as MacPorts install user.} {
    pre-configure {
        if { ${install.user}=="root" || ${install.group}=="wheel" } {
            ui_error "The DBUS daemon should not be run as root."
            error "Please do not use this variant with your MacPorts configuration."
        }
    }
    
    # Files are installed into user's startup directory.
    if { [tbool startupitem.install] } {
        destroot.violate_mtree  yes
    }
}

variant underscore conflicts no_root description {Put underscore in front of DBUS daemon user} {
    # For darwin ${os.major} > 8, daemon users have an underscore in front of the usernames and groups.
    # This variant allows the user to follow that convention.
}

set cross_opts  "ac_cv_have_abstract_sockets=no"
if {${os.arch} eq "i386"} {
    if { ${os.major} >= 10 } {
        set merger_configure_env(ppc) ${cross_opts}
    }
    set merger_configure_env(ppc64)   ${cross_opts}
} else {
    set merger_configure_env(i386)    ${cross_opts}
    set merger_configure_env(x86_64)  ${cross_opts}
}

livecheck.type  regex
livecheck.url   [lindex ${master_sites} 0]
livecheck.regex {dbus-(\d+\.\d*[02468](\.\d+)*)\.tar}
