# -*- 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                privoxy
version             4.0.0
revision            0
categories          www security net
license             GPL-2
maintainers         {ieee.org:s.t.smith @essandess} openmaintainer
supported_archs     arm64 x86_64

description         Advanced filtering web proxy

long_description    Privoxy is a web proxy with advanced filtering \
                    capabilities for protecting privacy, modifying web page \
                    content, managing cookies, controlling access, and \
                    removing ads, banners, pop-ups and other obnoxious \
                    Internet junk. Privoxy has a very flexible configuration \
                    and can be customized to suit individual needs and tastes. \
                    Privoxy has application for both stand-alone systems and \
                    multi-user networks.

homepage            https://www.privoxy.org/

set tls_ca_dir      ${prefix}/etc/${name}/ca.macports
set privoxy_ca_dir  ${prefix}/etc/${name}/CA
set user_pki_bundle ${privoxy_ca_dir}/user-pki-bundle.pem

set privoxyGroup    privoxy
set privoxyUser     privoxy
add_users           ${privoxyUser} group=${privoxyGroup}

# https://trac.macports.org/ticket/45461
configure.asroot    yes
pre-configure {
    # ${prefix}/var/macports/sources/rsync.macports.org/macports/release/tarballs/base/src/port1.0/portutil.tcl
    if {[getuid] != 0} {
        ui_warn "dscl only works when running as root."
        ui_warn "The PrimaryGroupID of '$privoxyUser' was not changed."
    } elseif {${os.platform} eq "darwin" \
        && [existsuser ${privoxyUser}] != -1 \
        && [existsgroup ${privoxyGroup}] != -1} {
        set dscl [findBinary dscl $portutil::autoconf::dscl_path]
        set privoxyUser_gid [strsed [exec -ignorestderr $dscl . -read /Users/${privoxyUser} PrimaryGroupID] {g|^PrimaryGroupID: ||}]
        if {${privoxyUser_gid} ne [existsgroup ${privoxyGroup}]} {
            exec -ignorestderr $dscl . -change /Users/${privoxyUser} PrimaryGroupID ${privoxyUser_gid} [existsgroup ${privoxyGroup}]
        }
    }
}

proc plutil_startup {plcmds label} {
    global prefix startupitem.location
    foreach cmd ${plcmds} {
        system -W ${prefix}/etc/${startupitem.location}/${label} \
            "/usr/bin/plutil ${cmd} ${label}.plist"
    }
}

if {${name} eq ${subport}} {
    PortGroup       gpg_verify 1.0
    PortGroup       perl5 1.0

    master_sites    ${homepage}/sf-download-mirror/Sources/${version}%20%28stable%29
    distname        ${name}-${version}-stable-src
    distfiles       ${distname}${extract.suffix}
    extract.only    ${distname}${extract.suffix}

    checksums       ${distname}${extract.suffix} \
                    rmd160  675fc82e27446ebc881693269d41c9af60d3a14c \
                    sha256  c08e2ba0049307017bf9d8a63dd2a0dfb96aa0cdeb34ae007776e63eba62a26f \
                    size    1746840

    gpg_verify.use_gpg_verification \
                    yes

    if {[option gpg_verify.use_gpg_verification]} {
        distfiles-append \
                    ${distname}${extract.suffix}.asc
        checksums-append \
                    ${distname}${extract.suffix}.asc \
                    size    833

        post-checksum {
            gpg_verify.verify_gpg_signature \
                    ${filespath}/keyid-691822918BA2371C.txt \
                    ${distpath}/${distname}${extract.suffix}.asc \
                    ${distpath}/${distname}${extract.suffix}
        }
    }

    # Please use MacPorts default perl5 version in:
    # https://github.com/macports/macports-ports/blob/master/_resources/port1.0/group/perl5-1.0.tcl
    perl5.major     5.34

    worksrcdir      ${name}-${version}-stable

    depends_lib-append \
                    port:brotli \
                    port:pcre \
                    port:zlib

    depends_run-append \
                    port:perl${perl5.major} \
                    port:p${perl5.major}-getopt-long \
                    port:p${perl5.major}-time-local

    # bash commands to generate patch files from new upstream configuration files
    ## export prefix=${prefix:-/opt/local}
    ## mkdir privoxy-orig privoxy-new
    ## sudo cp ${prefix}/etc/privoxy/config.new privoxy-orig/config
    ## sudo cp ${prefix}/etc/privoxy/match-all.action.new privoxy-orig/match-all.action
    ## sudo cp ./privoxy-orig/config ./privoxy-new/
    ## sudo cp ./privoxy-orig/match-all.action ./privoxy-new/
    ## sudo chown `whoami` privoxy-orig/config privoxy-new/config privoxy-orig/match-all.action privoxy-new/match-all.action
    ## patch -p0 -f -l -N privoxy-new/config < "$(dirname $(port file privoxy))/files/patch-config.diff"
    ## patch -p0 -f -l -N privoxy-new/match-all.action < "$(dirname $(port file privoxy))/files/patch-match-all.action.diff"
    ## diff -NaurdwB ./privoxy-orig/config ./privoxy-new/config | sed -E -e 's/\.\/privoxy-(orig|new)/\./g' | sed -E -e 's|/opt/local|@@PREFIX@@|g' > ~/Downloads/patch-config.diff
    ## diff -NaurdwB ./privoxy-orig/match-all.action ./privoxy-new/match-all.action | sed -E -e 's/\.\/privoxy-(orig|new)/\./g' | sed -E -e 's|/opt/local|@@PREFIX@@|g' > ~/Downloads/patch-match-all.action.diff

    # bash commands to patch existing configuration files from new upstream
    ## sudo cp ${prefix}/etc/privoxy/config.new privoxy-orig/config
    ## sudo cp ${prefix}/etc/privoxy/config privoxy-new/config
    ## diff -NaurdwB -I '^#[[:space:]]*' ./privoxy-orig/config ./privoxy-new/config | sed -E -e 's/\.\/privoxy-(orig|new)/\./g' > ~/Downloads/patch-my-config.diff
    ## patch -p0 -f -l -N -b privoxy-orig/config < ~/Downloads/patch-my-config.diff
    ## sudo cp ${prefix}/etc/privoxy/match-all.action.new privoxy-orig/match-all.action
    ## sudo cp ${prefix}/etc/privoxy/match-all.action privoxy-new/match-all.action
    ## diff -NaurdwB -I '^#[[:space:]]*' ./privoxy-orig/match-all.action ./privoxy-new/match-all.action | sed -E -e 's/\.\/privoxy-(orig|new)/\./g' > ~/Downloads/patch-my-match-all.action.diff
    ## patch -p0 -f -l -N -b privoxy-orig/match-all.action < ~/Downloads/patch-my-match-all.action.diff

    patchfiles-append \
                    patch-config.diff

    post-patch {
        reinplace "s|@@PREFIX@@|${prefix}|g" \
                    ${worksrcpath}/config
    }

    pre-configure {
        if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
            configure.args-append \
                    --with-user=${privoxyUser} \
                    --with-group=${privoxyGroup}
        }
        system -W ${worksrcpath} "autoheader"
    }

    use_autoconf    yes
    configure.args  --sysconfdir=${prefix}/etc/${name} \
                    --mandir=${prefix}/share/man \
                    --enable-compression \
                    --enable-dynamic-pcre \
                    --enable-zlib \
                    --with-brotli

    # work around bug 30345
    post-configure {
        file delete ${workpath}/.CC_PRINT_OPTIONS
    }

    # man page; reinplace paths for stability across version updates
    post-build {
        reinplace -E "s#(\\\\fI)((/(etc|var|log))+/privoxy(/\[-.*\[:alnum:]]*)*\\\\fR)#\\1${prefix}\\2#g" \
            ${worksrcpath}/${name}.8
        reinplace -E "s#(\\\\fI)/usr((/\[-.*\[:alnum:]]*)*/privoxy(/\[-.*\[:alnum:]]*)*\\\\fR)#\\1${prefix}\\2#g" \
            ${worksrcpath}/${name}.8
    }

    destroot.keepdirs \
                    ${destroot}${prefix}/var/log/${name} \
                    ${destroot}${prefix}/var/run

    post-destroot {
        # install Privoxy tools
        xinstall -d ${destroot}${prefix}/etc/${name}/tools
        foreach f [glob ${worksrcpath}/tools/*.pl] {
            set pl [file tail ${f}]
            xinstall -m 0755 ${f} ${destroot}${prefix}/etc/${name}/tools
            reinplace -W ${destroot}${prefix}/etc/${name}/tools -E \
                "1 s|^(#!)/usr/bin/perl|\\1${perl5.bin}|" \
                ${pl}
        }

        xinstall -d ${destroot}${prefix}/var/run
        # Install and fixup startup script (if non-Darwin)
        if {${os.platform} ne "darwin"} {
            xinstall -d ${destroot}${prefix}/etc/rc.d
            xinstall -m 0755 -W ${worksrcpath} privoxy-generic.init \
                    ${destroot}${prefix}/etc/rc.d/${name}.sh

            system -W ${destroot}${prefix}/etc/rc.d "patch -p0 < ${filespath}/patch-privoxy.sh.diff"
            reinplace "s|@@PREFIX@@|${prefix}|g" \
                    ${destroot}${prefix}/etc/rc.d/${name}.sh
            if {[existsuser ${privoxyUser}] != 0} {
                reinplace "s|@@PRIVOXY_USER@@|${privoxyUser}|g" \
                    ${destroot}${prefix}/etc/rc.d/${name}.sh
            } else {
                reinplace "s|@@PRIVOXY_USER@@|$env(USER)|g" \
                    ${destroot}${prefix}/etc/rc.d/${name}.sh
            }
        }
        # Rename these so local modifications are not removed on uninstall.
        # NOTE: Always overwrite default.action and default.filter.
        foreach privoxyConf {config match-all.action trust user.action user.filter} {
            if {[file exists ${destroot}${prefix}/etc/${name}/${privoxyConf}]} {
                file rename ${destroot}${prefix}/etc/${name}/${privoxyConf} \
                    ${destroot}${prefix}/etc/${name}/${privoxyConf}.new
            }
            # backup config files before fix #23970
            if {[file exists ${prefix}/etc/${name}/${privoxyConf}] \
                && ![file exists ${prefix}/etc/${name}/${privoxyConf}.new]} {
                file copy ${prefix}/etc/${name}/${privoxyConf} \
                    ${destroot}${prefix}/etc/${name}/${privoxyConf}.mp_backup
            }
        }
        # Remove the preinstalled log files as, otherwise, a rotation script
        # will fail when trying to rename and compress due to gzip not liking
        # multi-linked files (the one in ${prefix} and the one in
        # ${prefix}/var/db/dports/software/...)
        file delete {*}[glob ${destroot}${prefix}/var/log/${name}/*]
        if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
            # Make sure log directory owned by privoxy user/group
            file attributes ${destroot}${prefix}/var/log/${name} \
                    -group ${privoxyGroup} -owner ${privoxyUser}
        }
    }

    post-activate {
        # Make sure initial log files are present and setup correctly
        foreach privoxyLog {jarfile logfile} {
            touch ${prefix}/var/log/${name}/${privoxyLog}
            if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
                file attributes ${prefix}/var/log/${name}/${privoxyLog} \
                    -group ${privoxyGroup} -owner ${privoxyUser} \
                    -permissions 0660
            }
        }
        foreach privoxyConf {config match-all.action trust user.action user.filter} {
            if {![file exists ${prefix}/etc/${name}/${privoxyConf}]} {
                # restore config files before fix #23970
                if {[file exists ${prefix}/etc/${name}/${privoxyConf}.mp_backup]} {
                    file copy ${prefix}/etc/${name}/${privoxyConf}.mp_backup \
                        ${prefix}/etc/${name}/${privoxyConf}
                } else {
                    file copy ${prefix}/etc/${name}/${privoxyConf}.new \
                        ${prefix}/etc/${name}/${privoxyConf}
                }
                if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
                    file attributes ${prefix}/etc/${name}/${privoxyConf} \
                        -group ${privoxyGroup} -owner ${privoxyUser} \
                        -permissions 0660
                }
            }
        }
    }

    variant https_inspection \
        description {Use Privoxy HTTPS inspection.} {
        depends_build-append \
                    port:sf-pwgen

        depends_lib-append \
                    path:bin/openssl:openssl \
                    path:lib/libssl.dylib:openssl

        depends_run-append \
                    port:${name}-pki-bundle

        patchfiles-append \
                    patch-match-all.action.diff

        post-patch {
            reinplace -E "s|^#(ca-directory )|\\1|" \
                    ${worksrcpath}/config
            reinplace -E "s|^#(certificate-directory )|\\1|" \
                    ${worksrcpath}/config
        }

        # random 4-word-based passphrase
        proc correct_horse_battery_staple {} {
            # ignore errors from sf-pwgen if the password is shorter than requested
            set passphrase \
                [join [exec sh -c "sf-pwgen \
                    --algorithm memorable --count 2 --length 16 \
                        2>/dev/null || true"] -]
            # set random passphrase if sf-pwgen's is too short for some reason
            if {[string length ${passphrase}] < 20} {
                set passphrase \
                    [exec sh -c "openssl rand -base64 23 2>/dev/null \
                        | sed 's|=*\$||' || true"]
            }
            return ${passphrase}
        }

        configure.args-append \
                --with-openssl

        destroot.keepdirs-append \
                ${destroot}${privoxy_ca_dir} \
                ${destroot}${prefix}/var/${name} \
                ${destroot}${prefix}/var/${name}/certs

        post-destroot {
            xinstall -d \
                ${destroot}${privoxy_ca_dir} \
                ${destroot}${prefix}/var/${name} \
                ${destroot}${prefix}/var/${name}/certs

            if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
                file attributes ${destroot}${privoxy_ca_dir} \
                    -group ${privoxyGroup} -owner ${privoxyUser}
                file attributes ${destroot}${prefix}/var/${name} \
                    -group ${privoxyGroup} -owner ${privoxyUser}
                file attributes ${destroot}${prefix}/var/${name}/certs \
                    -group ${privoxyGroup} -owner ${privoxyUser}
            }

            # TLS Root CA configuration
            xinstall -d ${destroot}${tls_ca_dir}
            xinstall -m 0700 -d ${destroot}${tls_ca_dir}/private
            destroot.keepdirs-append \
                    ${destroot}${tls_ca_dir} \
                    ${destroot}${tls_ca_dir}/private
            foreach d {certs crl newcerts} {
                xinstall -d \
                    ${destroot}${tls_ca_dir}/${d}
                destroot.keepdirs-append \
                    ${destroot}${tls_ca_dir}/${d} \
                }
            xinstall -m 0644 \
                    ${filespath}/openssl.cnf \
                    ${destroot}${tls_ca_dir}
        }

        pre-activate {
            if { [file exists ${tls_ca_dir}] } {
                delete \
                    ${tls_ca_dir}.previous
                move \
                    ${tls_ca_dir} \
                    ${tls_ca_dir}.previous
            }
        }

        post-activate {
            # CA passphrase
            # generate a strong password, use for openssl -passin and -passout
            set tls_ca_passphrase \
                    [correct_horse_battery_staple]
            set tls_ca_passphrase_fd \
                    [open ${tls_ca_dir}/private/passphrase.txt w 0600]
            # -passin or -passout
            puts ${tls_ca_passphrase_fd} \
                    ${tls_ca_passphrase}
            # -passout
            puts ${tls_ca_passphrase_fd} \
                    ${tls_ca_passphrase}
            close ${tls_ca_passphrase_fd}
            # create the root CA
            system -W ${tls_ca_dir} \
                "sh <<TLS_PRIVOXY_ROOT_CA
                # initialize
                touch index.txt
                echo '01' > serial

                # CA encrypted key
                # EC
                openssl genpkey -out private/ca.key.pem -algorithm EC \\
                    -pkeyopt ec_paramgen_curve:P-384 -aes256 \\
                    -pass file:private/passphrase.txt

                # RSA
                # openssl genpkey -out private/ca.key.pem -algorithm RSA \\
                #     -pkeyopt rsa_keygen_bits:2048 -aes256 \\
                #     -passout file:private/passphrase.txt

                chmod go-rw private/ca.key.pem

                # CA certificate
                openssl req -config openssl.cnf \\
                    -new -x509 -days 1460 -sha384 \\
                    -extensions v3_ca \\
                    -out certs/ca.cert.pem -key private/ca.key.pem \\
                    -passin file:private/passphrase.txt -batch

                # CA certificate openssl self-verification
                openssl verify -CAfile certs/ca.cert.pem certs/ca.cert.pem

                # Convert to .cer DER and .p12 for other uses
                openssl x509 -outform der -in certs/ca.cert.pem -out certs/ca.cer

                # https://developer.apple.com/forums/thread/697030
                openssl pkcs12 -legacy -export -out certs/ca.p12 \\
                    -inkey private/ca.key.pem -in certs/ca.cert.pem \\
                    -passin file:private/passphrase.txt \\
                    -passout file:private/passphrase.txt
                # verify .p12 passphrase
                openssl pkcs12 -legacy -noout \\
                    -in certs/ca.p12 -passin file:private/passphrase.txt
TLS_PRIVOXY_ROOT_CA
"

            if { ![file exists ${privoxy_ca_dir}/ca.cert.pem]
                || ![file exists ${privoxy_ca_dir}/ca.key.pem] } {
                xinstall -m 0664 \
                    ${tls_ca_dir}/certs/ca.cert.pem \
                    ${privoxy_ca_dir}
                xinstall -m 0664 \
                    ${tls_ca_dir}/private/ca.key.pem \
                    ${privoxy_ca_dir}
                xinstall -m 0664 \
                    ${tls_ca_dir}/certs/ca.cer \
                    ${privoxy_ca_dir}
                xinstall -m 0664 \
                    ${tls_ca_dir}/certs/ca.p12 \
                    ${privoxy_ca_dir}
                if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
                    file attributes ${privoxy_ca_dir}/ca.cert.pem \
                        -group ${privoxyGroup} -owner ${privoxyUser} \
                        -permissions 0664
                    file attributes ${privoxy_ca_dir}/ca.key.pem \
                        -group ${privoxyGroup} -owner ${privoxyUser} \
                        -permissions 0664
                    file attributes ${privoxy_ca_dir}/ca.cer \
                        -group ${privoxyGroup} -owner ${privoxyUser} \
                        -permissions 0664
                    file attributes ${privoxy_ca_dir}/ca.p12 \
                        -group ${privoxyGroup} -owner ${privoxyUser} \
                        -permissions 0664
                }
            }
            # Do not overwrite ca-password, but this is where it goes
            # reinplace -E -q "s|^#(ca-password\[\[:space:]]+)\[^\[:space:]]*)|\\1${tls_ca_passphrase}|" \
            #     ${prefix}/etc/${name}/config
        }

        notes \
            "Edit ${prefix}/etc/${name}/match-all.action to specify\
            which domains will use https-inspection.

            Configure HTTPS inspection by creating a local Privoxy\
            certificate authority (CA). As sudo:

            cp -R ${prefix}/etc/${name}/ca.macports ca.hostname && cd ca.hostname
            # edit openssl.cnf for your local organizationName, commonName, etc.

            # generate a strong password, use for both -passin and -passout
            # avoid passphrases with '#' as the passphrase is set in config
            sf-pwgen --algorithm memorable --count 2 --length 24 2>/dev/null \\
                | paste -s -d -- '-' 1> private/passphrase.txt
            cat private/passphrase.txt private/passphrase.txt \\
                > private/passphrase-dbl.txt \\
                && mv private/passphrase-dbl.txt private/passphrase.txt \\
                || rm -f private/passphrase-dbl.txt
            chmod go-rwx private/passphrase.txt

            # private key (EC)
            openssl genpkey -out private/ca.key.pem -algorithm EC \\
                -pkeyopt ec_paramgen_curve:P-384 -aes256 \\
                -pass file:private/passphrase.txt

            # private key (RSA)
            # openssl genpkey -out private/ca.key.pem -algorithm RSA \\
            #     -pkeyopt rsa_keygen_bits:2048 -aes256 \\
            #     -pass file:private/passphrase.txt

            # Certificate PEM, DER, and P12
            openssl req -config openssl.cnf -new -x509 -days 3650 -sha384 \\
                -extensions v3_ca -out certs/ca.cert.pem \\
                -key private/ca.key.pem -passin file:private/passphrase.txt \\
                -batch
            openssl verify -CAfile certs/ca.cert.pem certs/ca.cert.pem
            openssl x509 -outform der -in certs/ca.cert.pem -out certs/ca.cer
            # https://developer.apple.com/forums/thread/697030
            openssl pkcs12 -legacy -export -out certs/ca.p12 -inkey private/ca.key.pem \\
                -in certs/ca.cert.pem -passin file:private/passphrase.txt \\
                -passout file:private/passphrase.txt
            # verify .p12 passphrase
            openssl pkcs12 -legacy -noout -in certs/ca.p12 \\
                -passin file:private/passphrase.txt

            # Install the Privoxy PKI
            cp -p private/ca.key.pem certs/ca.cert.pem certs/ca.cer certs/ca.p12 \\
                ${privoxy_ca_dir}
            # Edit ${prefix}/etc/${name}/config and set ca-password

            # Import and trust the CA in Keychain Access
            Keychain\\ Access.app> Import ca.cer or ca.p12 into \
                the System keychain, trust for X.509.

            # Disable MITM for the CA on some FF configurations
            Firefox.app> about:config> security.enterprise_roots.enabled> true"

        # Add notes if this is installed: ${name}-pki-bundle +user_pki_bundle
        if { ![catch {set result [registry_active ${name}-pki-bundle]}]
            && [string match "*+user_pki_bundle*" [lindex [lindex ${result} 0] 3]] } {
            if {[exists notes]} {
                # leave a blank line after the existing notes
                notes-append ""
            }
            notes-append "User PKI certificates will be added from the file\
                    ${user_pki_bundle} (ASCII PEM file)\
            via the port '${name}-pki-bundle +user_pki_bundle'.
"
        }
    }

    variant ecc \
        requires    https_inspection \
        description {Use Elliptic Curve Keys for HTTPS Inspection.} {
        # diff -NaurdwB ./privoxy-orig/openssl.c ./privoxy-new/openssl.c | sed -E -e 's/\.\/privoxy-(orig|new)/\./g' > ~/Downloads/patch-openssl.c.diff
        # diff -NaurdwB ./privoxy-orig/ssl_common.h ./privoxy-new/ssl_common.h | sed -E -e 's/\.\/privoxy-(orig|new)\//\.\//' > ~/Downloads/patch-ssl_common.h.diff
        patchfiles-append \
                    patch-openssl.c.diff \
                    patch-ssl_common.h.diff
        }

    default_variants-append \
                    +https_inspection

    startupitem.create \
                    yes
    startupitems \
        name        Privoxy \
        init        "pidfile=\"\${prefix}/var/run/${name}.pid\"" \
        start [list "\[ -f \"\${prefix}/etc/${name}/config\" \] \\" \
                    "\t&& \"\${prefix}/sbin/${name}\" \\" \
                    "\t\t--pidfile \"\${pidfile}\" \\" \
                    "\t\t--user ${privoxyUser} \\" \
                    "\t\t\"${prefix}/etc/${name}/config\" 2>/dev/null" \
        ] \
        stop [list  "if \[ -f \"\${pidfile}\" \]; then" \
                    "\tkill \$(cat \"\${pidfile}\") \\" \
                    "\t\t&& rm -f \"\${pidfile}\"" \
                    "else" \
                    "\t/usr/bin/killall -SIGUSR1 privoxy 2>/dev/null" \
                    "fi" \
        ] \
        pidfile     [list auto ${prefix}/var/run/${name}.pid]

    if { [variant_isset "https_inspection"] } {
        startupitems-append \
            name    Privoxy.delete-expired-certs \
            executable  \
                    /bin/bash \
            pidfile none

        post-activate {
            # bruteforce expiration launchd daemon
            # Privoxy certs are issued for 30 days; delete every week
            plutil_startup [list \
                "-insert Program -string /bin/bash" \
                "-replace ProgramArguments \
                    -xml '<array> \
                      <string>/bin/bash</string> \
                      <string>-c</string> \
                      <string>for c in ${prefix}/var/${name}/certs/*.crt; do if ! openssl x509 -checkend 0 -noout -in &quot;\${c}&quot; 1&gt; /dev/null 2&gt;&amp;1; then rm -f &quot;\${c}&quot; &quot;\${c%.crt}.pem&quot;; fi; done</string> \
                    </array>'" \
                "-remove KeepAlive" \
                "-insert StartCalendarInterval \
                    -xml '<dict> \
                      <key>Weekday</key> \
                      <integer>7</integer> \
                      <key>Hour</key> \
                      <integer>0</integer> \
                      <key>Minute</key> \
                      <integer>30</integer> \
                    </dict>'" \
                ] \
                org.macports.Privoxy.delete-expired-certs
        }
    }

    livecheck.type  regex
    livecheck.url   ${homepage}announce.txt
    livecheck.regex Announcing Privoxy (\[0-9.\]+)
}

subport ${name}-pki-bundle {
    # Please increase the revision whenever curl-ca-bundle contents change
    revision        0

    license         MIT
    supported_archs noarch
    platforms       any

    description     PKI Bundle for ${name}
    long_description \
                    {*}${description}

    master_sites
    distfiles
    extract.only

    depends_lib-append \
                    port:apple-pki-bundle \
                    path:share/curl/curl-ca-bundle.crt:curl-ca-bundle

    use_configure   no
    build           {}

    destroot {
        xinstall -d ${destroot}${privoxy_ca_dir}

        if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
            file attributes ${destroot}${privoxy_ca_dir} \
                    -group ${privoxyGroup} -owner ${privoxyUser}
        }

        # cat all trusted PKI bundles to a single file
        system -W ${destroot}${privoxy_ca_dir} \
            "${prefix}/share/apple-pki-bundle/bin/pems_that_wont_expire_soon.sh \
                ${prefix}/share/apple-pki-bundle/apple-pki-bundle.pem \
                    >> ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp"
        copy        ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp \
                    ${destroot}${privoxy_ca_dir}/trustedCAs.pem
        system -W ${destroot}${privoxy_ca_dir} \
            "${prefix}/share/apple-pki-bundle/bin/pems_not_in_pemfile.sh \
                ${prefix}/share/curl/curl-ca-bundle.crt \
                ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp \
                    >> ${destroot}${privoxy_ca_dir}/trustedCAs.pem"
        if { [variant_isset "user_pki_bundle"] \
            && [file exists ${user_pki_bundle}]} {
            delete  ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp
            copy    ${destroot}${privoxy_ca_dir}/trustedCAs.pem \
                    ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp
            system -W ${destroot}${privoxy_ca_dir} \
                "${prefix}/share/apple-pki-bundle/bin/pems_not_in_pemfile.sh \
                    ${user_pki_bundle} \
                    ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp \
                        >> ${destroot}${privoxy_ca_dir}/trustedCAs.pem"
        }
        delete      ${destroot}${privoxy_ca_dir}/trustedCAs.pem-temp

        if {[existsuser ${privoxyUser}] != 0 && [existsgroup ${privoxyGroup}] != 0} {
            file attributes \
                ${destroot}${privoxy_ca_dir}/trustedCAs.pem \
                    -group ${privoxyGroup} -owner ${privoxyUser} \
                    -permissions 0664
        }
    }
    destroot.keepdirs-append \
                    ${destroot}${privoxy_ca_dir}

    variant user_pki_bundle \
        description "Add user PKI certificates from ${user_pki_bundle}" {
        notes "User PKI certificates will be added from the file\
                    ${user_pki_bundle} (ASCII PEM file)."
    }

    default_variants-append \
                    +user_pki_bundle

    livecheck       none
}
