# -*- 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                certsync
version             1.1.3
categories          security
conflicts           curl-ca-bundle
maintainers         {landonf @landonf} openmaintainer
description         Export x509 CAs from the Mac OS X Keychain.
long_description    \
    The package implements exporting of x509 CAs from the Mac OS X keychain, \
    for use by OpenSSL and gnutls.
homepage            https://www.macports.org/
license             MIT
platforms           darwin

installs_libs       no

distfiles

extract.mkdir       yes
post-extract {
    xinstall -m 644 -W ${filespath} certsync.m compat.h certsync.plist update-ca-certificates ${worksrcpath}
}

post-patch {
    reinplace "s|@PREFIX@|${prefix}|g" \
        ${worksrcpath}/update-ca-certificates \
        ${worksrcpath}/certsync.plist

    reinplace "s|@LABEL@|${startupitem.uniquename}|g" ${worksrcpath}/certsync.plist
}

use_configure       no

variant universal {}

# We inject our own launchd plist to allow the use of WatchPaths
startupitem.create  no
startupitem.type    launchd
startupitem.autostart yes

build {
    system -W ${worksrcpath} "${configure.objc} \
        ${configure.objcflags} \
        -mmacosx-version-min=${macosx_deployment_target} \
        -Wall \
        certsync.m -o certsync \
        ${configure.ldflags} \
        [get_canonical_archflags ld] \
        -framework Foundation -framework Security -framework CoreServices"
}

destroot {
    # Install the binaries
    xinstall -m 755 -W ${worksrcpath} certsync ${destroot}${prefix}/libexec
    xinstall -m 755 -W ${worksrcpath} update-ca-certificates ${destroot}${prefix}/bin

    # Install our custom plist
    set launchd_dir "${prefix}/etc/${startupitem.location}/${startupitem.uniquename}"
    xinstall -m 755 -d ${destroot}/${launchd_dir}
    xinstall -m 644 -W ${worksrcpath} certsync.plist  ${destroot}/${launchd_dir}/${startupitem.plist}

    if {[getuid] == 0 && ${startupitem.install} != "no"} {
        file mkdir "${destroot}/Library/${startupitem.location}"
        ln -sf "${launchd_dir}/${startupitem.plist}" "${destroot}/Library/${startupitem.location}"
    } else {
        ln -sf ${launchd_dir}/${startupitem.plist} ${destroot}${prefix}/etc/${startupitem.location}
    }

    # Provide backwards compatibility with curl-ca-bundle
    xinstall -d "${destroot}${prefix}/share/curl"
    ln -s ${prefix}/etc/openssl/cert.pem ${destroot}${prefix}/share/curl/curl-ca-bundle.crt
}

post-activate {
    system "${prefix}/bin/update-ca-certificates"
}

pre-deactivate {
    delete "${prefix}/etc/openssl/cert.pem"
}