# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4

PortSystem          1.0
PortGroup           active_variants 1.1

name                zabbix4
revision            1
categories          net
maintainers         {eborisch @eborisch} openmaintainer

# https://github.com/zabbix/zabbix/commit/eeeb4c8756
license             {GPL-2+ OpenSSLException}

description         An open source application and network monitor

long_description    Zabbix is the ultimate open source availability and \
                    performance monitoring solution. Zabbix offers advanced \
                    monitoring, alerting, and visualization features today \
                    which are missing in other monitoring systems, even some \
                    of the best commercial ones.

array set VERSIONS {
    4  4.0.41
    5  5.0.24
    #6  6.0.1  # Haven't had a chance to test yet.
}

set zver            [regsub -all {[^\d]} ${subport} {}]
version             $VERSIONS(${zver})
set zbranch         [regsub {\.[\drc]+$} ${version} {}]

distname            zabbix-${version}
livecheck.name      zabbix

livecheck.url \
    https://www.zabbix.com/download_sources
homepage            http://www.zabbix.com/
master_sites \
    https://cdn.zabbix.com/zabbix/sources/stable/${zbranch}

dist_subdir         zabbix${zver}

if {$zver == 4} {
    livecheck.regex     "zabbix-(4\\.0\\.\[0-9\]+).tar.gz"
    checksums \
        rmd160  968d21baaa20a8927d19699fa6efcce2faa41793 \
        sha256  362139c1e52680501059a38251dadf3dc692da2e14c7defe095649cfa483baad \
        size    17641873
}

if {$zver == 5} {
    livecheck.regex     "zabbix-(5\\.0\\.\[0-9\]+).tar.gz"
    checksums \
        rmd160  b3e4baed42ba5f5f23f8aa7afab7057b01411bb8 \
        sha256  79e5740ea5038cf52072fe7c3eaa033511f473b896029cef442b2920fd6eac79 \
        size    21296805
}

if {$zver == 6} {
    livecheck.regex     "zabbix-(6\\.0\\.\[0-9\]+).tar.gz"
    checksums \
        rmd160  1c763ee59a26004a6c0dec863e6beaa730bf281e \
        sha256  2dd92383cc169ce8b8cbbe660ed656e5d6b5b75bf4936743b8a9d59cdfcf3af1 \
        size    32974585
}

patchfiles          log_and_pid_locations.patch

universal_variant   no

# LTS Versions
subport             zabbix4             {conflicts zabbix5 zabbix6}
subport             zabbix4-agent       {conflicts zabbix5-agent zabbix6-agent}
subport             zabbix4-frontend    {conflicts zabbix5-frontend zabbix6-frontend}

subport             zabbix5             {conflicts zabbix4 zabbix6}
subport             zabbix5-agent       {conflicts zabbix4-agent zabbix6-agent}
subport             zabbix5-frontend    {conflicts zabbix4-frontend zabbix6-frontend}

#subport             zabbix6             {conflicts zabbix4 zabbix5}
#subport             zabbix6-agent       {conflicts zabbix4-agent zabbix5-agent}
#subport             zabbix6-frontend    {conflicts zabbix4-frontend zabbix5-frontend}

proc isFlavor {desc subp} {
    return [expr {[string first ${desc} ${subp}] >= 0}]
}

configure.args      --bindir=${prefix}/bin/zabbix \
                    --sbindir=${prefix}/sbin/zabbix \
                    --libexecdir=${prefix}/libexec/zabbix \
                    --datadir=${prefix}/share/zabbix \
                    --sysconfdir=${prefix}/etc/zabbix${zver} \
                    --localstatedir=${prefix}/var/zabbix \
                    --with-gnutls=${prefix} \
                    --enable-ipv6 \
                    --with-libevent=${prefix} \
                    --with-libpcre=${prefix}

configure.ldflags-append    -lresolv

if {![isFlavor frontend ${subport}]} {
    startupitem.create      yes
    depends_lib-append      port:libiconv \
                            path:lib/pkgconfig/gnutls.pc:gnutls \
                            port:pcre \
                            port:libevent
}

if {[isFlavor agent ${subport}]} {
    long_description-append "\n * ${subport} provides a local monitoring agent."
    conflicts-append        zabbix3-agent
    startupitem.name        zabbix${zver}-agentd
    startupitem.executable  \
        ${prefix}/sbin/zabbix/zabbix_agentd \
        -c ${prefix}/etc/zabbix${zver}/zabbix_agentd.conf
    startupitem.pidfile     auto ${prefix}/var/run/zabbix/zabbix_agentd.pid
    startupitem.logfile     ${prefix}/var/log/zabbix/zabbix_agentd.launch

    configure.args-append   --enable-agent
    
    # Revisit if/when upstream supports building on OSX
    #if {$zver == 44} {
    #    configure.args-append   --enable-agent2
    #    build.env-append    GOPATH=${worksrcpath}/src/zabbix
    #}

    destroot.keepdirs \
        ${destroot}${prefix}/etc/zabbix${zver}/zabbix_agentd.conf.d \
        ${destroot}${prefix}/var/run/zabbix \
        ${destroot}${prefix}/var/log/zabbix
} elseif {[isFlavor frontend ${subport}]} {
    long_description-append "\n * ${subport} provides the web (PHP) frontend."
    supported_archs         noarch
    platforms               any
    depends_run-append      port:apache2

    variant nls description "Include translation files." {
    }

    if { [vercmp $version 5.0.0 ] < 0 } {
        set phplist {php56 php74}
    } else {
        set phplist {php74}
    }

    foreach php "${phplist}" {
        variant ${php} description "Use ${php}" "
            depends_run-append      port:${php} \
                                    port:${php}-apache2handler \
                                    port:${php}-gd \
                                    port:${php}-gettext \
                                    port:${php}-mbstring \
                                    port:${php}-sockets
        "
    }

    if {![variant_isset php56] && ![variant_isset php74]} {
        default_variants        +php74
    }
    use_configure           no
    build {}
    # Kept in post-destroot sections below for consistency
    destroot {}
} else {
    long_description-append "This port provides the central server component."
    conflicts-append        zabbix3

    depends_build-append    port:pkgconfig
    depends_lib-append      port:curl \
                            port:OpenIPMI \
                            path:lib/libssl.dylib:openssl \
                            port:libssh2 \
                            port:libxml2 \
                            port:net-snmp \
                            port:zlib

    depends_run-append      port:fping

    configure.args-append   --enable-server \
                            --with-libcurl=${prefix}/bin/curl-config \
                            --with-net-snmp \
                            --with-openipmi=${prefix} \
                            --with-ssh2=${prefix} \
                            --with-libxml2=${prefix}/bin/xml2-config\
                            --with-zlib=${prefix}

    startupitem.name        zabbix${zver}-server
    startupitem.start       ${prefix}/sbin/zabbix/zabbix_server
    set pidfile             ${prefix}/var/run/zabbix/zabbix_server.pid
    # Gracefully wait up to two minutes for zabbix to shut down / clean up
    startupitem.stop \
        "let x=120; while /usr/bin/pkill -u zabbix -F ${pidfile}; \
         do sleep 1; let x--; \[ \$x -le 0 \] && break; done"
    startupitem.logfile     ${prefix}/var/log/zabbix/zabbix_server.launch
    startupitem.netchange   yes

    # This *increases* the values if needed, but otherwise leaves them alone.
    startupitem.init \
        {bump() { [ `sysctl -n $1` -lt $2 ] && sysctl $1=$2 ; } } \
        "bump kern.sysv.shmall 32768 && bump kern.sysv.shmmax 134217728"

    destroot.keepdirs \
        ${destroot}${prefix}/etc/zabbix${zver}/zabbix_server.conf.d \
        ${destroot}${prefix}/var/run/zabbix${zver} \
        ${destroot}${prefix}/var/log/zabbix

    variant full_server description {
        Dependencies for a complete server (w/DB) are installed.
    } {}
    
    variant frontend description {Include frontend PHP files / deps} {
        depends_run-append  port:zabbix${zver}-frontend
    }

    default_variants-append +frontend
}

if {![isFlavor agent ${subport}]} {
    # Logic for database backends. Needed for -frontend and -server
    # Items are "display name" "port name" "config arg" "php interface"
    array set DBLIST {
        mysql57 {"MySQL 5.7"            mysql57 \
                 mysql=${prefix}/lib/mysql57/bin/mysql_config mysql}
        mariadb105 {"MariaDB 10.5"         mariadb-10.5 \
                 mysql=${prefix}/lib/mariadb-10.5/bin/mysql_config mysql}
        pgsql13 {"PostgreSQL 13.x"      postgresql13 \
                 postgresql=${prefix}/lib/postgresql13/bin/pg_config postgresql}
    }

    set DBLIST_KEYS [lsort [array names DBLIST]]
    
    foreach dbitem $DBLIST_KEYS {
        set this_key [lsearch -exact $DBLIST_KEYS $dbitem]
        set conf_list [lreplace $DBLIST_KEYS $this_key $this_key]
        set prms $DBLIST($dbitem)
        
        variant $dbitem description \
          "Use [lindex ${prms} 0] for server database" \
          conflicts {*}${conf_list} "

            set ::ZDB               [lindex ${prms} 1]
            set ::DBFILES           [lindex ${prms} 3]
            set ::MYSQL_MODE        [string equal [lindex ${prms} 3] mysql]
            configure.args-append   --with-[lindex ${prms} 2]

            if {[isFlavor frontend ${subport}]} {
                if { [vercmp $version 5.0.0 ] < 0 } {
                    if {[variant_isset php56]} {
                        depends_run-append \
                            port:php56-[lindex ${prms} 3]
                    }
                }

                if {[variant_isset php74]} {
                    depends_run-append \
                        port:php74-[lindex ${prms} 3]
                }
            } else {
                depends_lib-append      port:[lindex ${prms} 1]
                require_active_variants port:zabbix${zver}-agent ${dbitem}
            }
        "
    }

    if {![variant_isset mysql57] &&
        ![variant_isset mariadb105] &&
        ![variant_isset pgsql13]} {
        default_variants            +mysql57
    }
}

post-extract {
    if {[string first - ${subport}] == -1} {
        if { ${MYSQL_MODE} == 1 &&
             [variant_isset full_server] } {
                set repstr "s|# DBSocket=|"
                append repstr "DBSocket=${prefix}/var/run/${ZDB}/mysqld.sock|"
            reinplace ${repstr} ${worksrcpath}/conf/zabbix_server.conf
        }
    }
    set repstr "s|# FpingLocation=/usr/sbin/fping|"
    append repstr "FpingLocation=${prefix}/sbin/fping|"
    reinplace ${repstr} ${worksrcpath}/conf/zabbix_server.conf
}

post-patch {
    reinplace "s|%%PREFIX%%|${prefix}|" \
        conf/zabbix_agentd.conf conf/zabbix_server.conf
    reinplace "s|/usr/local/etc|${prefix}/etc/zabbix${zver}|" \
        conf/zabbix_agentd.conf conf/zabbix_server.conf
}

add_users zabbix group=zabbix

post-destroot {
    if {[isFlavor agent ${subport}]} {
     ####### AGENT #######
# Copy sample agent .conf files
        xinstall -m 755 -d \
            ${destroot}${prefix}/etc/zabbix${zver}/zabbix_agentd.conf.d
        xinstall -m 755  ${worksrcpath}/conf/zabbix_agentd.conf \
            ${destroot}${prefix}/etc/zabbix${zver}/zabbix_agentd.conf.sample

# Don't overwrite user settings on each install
        delete ${destroot}${prefix}/etc/zabbix${zver}/zabbix_agentd.conf
    } elseif {[isFlavor frontend ${subport}]} {
# Copy the front end files
        set fedir ${destroot}${prefix}/share/zabbix/frontends
        file mkdir ${fedir}
        if {$zver >= 5} {
            file copy ${worksrcpath}/ui/ ${fedir}/php
        } else {
            file copy ${worksrcpath}/frontends/php/ ${fedir}
        }

        system -W ${fedir} "find . -type f -name *.po -delete"

        if {![variant_isset nls]} {
            system -W ${fedir}/php/locale \
                "find . -type f -name *.mo ! -path */en_US/* -delete"
            reinplace "/display/s/true/false/" \
                ${fedir}/php/include/locales.inc.php
            reinplace "/en_US/s/false/true/" \
                ${fedir}/php/include/locales.inc.php
        }

# Set permissions for etc (protect passwords) and the frontend
        system "chown -R www:www ${destroot}${prefix}/share/zabbix/frontends/*"
    } else {
     ####### SERVER #######
# Copy sample server and agent .conf files
        xinstall -m 755 -d \
            ${destroot}${prefix}/etc/zabbix${zver}/zabbix_server.conf.d

# Don't overwrite user settings on each install
        move ${destroot}${prefix}/etc/zabbix${zver}/zabbix_server.conf \
            ${destroot}${prefix}/etc/zabbix${zver}/zabbix_server.conf.sample

# Copy database data and schemas
        xinstall -m 755 -d ${destroot}${prefix}/share/zabbix/scripts

        xinstall -m 755 -W ${worksrcpath}/database/${DBFILES} \
            data.sql images.sql schema.sql \
            ${destroot}${prefix}/share/zabbix/scripts

        #file copy ${worksrcpath}/upgrades \
        #    ${destroot}${prefix}/share/zabbix/

        # Set permissions for etc (protect passwords)
        system "chmod ug+rwX,o-rwx ${destroot}${prefix}/etc/zabbix${zver}/*"
        system "chown -R zabbix:zabbix ${destroot}${prefix}/etc/zabbix${zver}"
    }

    foreach dname {run log} {
        xinstall -d -m 755 ${destroot}${prefix}/var/${dname}/zabbix
        system "chown -R zabbix:zabbix ${destroot}${prefix}/var/${dname}/zabbix"
    }

}

if {[isFlavor agent ${subport}]} {
    notes "
####
#### ZABBIX${zver} agent installation section

1) Edit the sample .conf file ${prefix}/etc/zabbix${zver}/zabbix_agentd.conf.sample
   (rename & omit .sample)

   Set the following variable to the IP address of your ZABBIX server to\
   allow it access to the agent.

    Server=x.x.x.x


2) Set zabbix_agentd to run at system boot

     sudo port load zabbix${zver}-agent

#### End ZABBIX${zver} agent installation section ####
####
"
} elseif {[isFlavor frontend ${subport}]} {
    notes "
####
#### Begin ZABBIX${zver} frontend installation section ####

1) Set a symbolic link in your Apache document root pointing to the PHP
   frontend files

    sudo ln -s ${prefix}/share/zabbix/frontends/php <Apache-docroot>/zabbix


2) Enable your desired php version in httpd.conf and make sure the following
   are set in the associated php.ini:
   
    max_execution_time = 300
    max_input_time = 300
    post_max_size = 16M
    date.timezone = < Your TZ; see http://php.net/manual/en/timezones.php >

   And for >= php56:
    always_populate_raw_post_data = -1


3) Open http://localhost/zabbix/ in your browser and walk through the setup,
   then login with default user 'Admin' and password 'zabbix'.


4) Read the fine manual at http://www.zabbix.com/documentation/

#### End ZABBIX${zver} frontend installation section   ####
####
"
} else {
    set shortver [regsub {\.\d+$} ${version} {}]
    notes "
####
#### Begin ZABBIX${zver} local server installation section ####

  !! LOADING ZABBIX${zver} WILL *INCREASE* THESE sysctl VALUES TO BE AT LEAST:
    kern.sysv.shmall=32768 kern.sysv.shmmax=134217728
  This can be adjusted in the file below, but resets after an upgrade:
    ${prefix}/etc/LaunchDaemons/org.macports.zabbix${zver}-server/zabbix${zver}-server.wrapper

 (Installing with +full_server will add all of the dependants; configuration
  will still be required.)

1) Setup your SQL server, i.e. via MacPorts: (for local SQL server; can be on
   a separate system.)

    sudo port install mysql5-server (or mariadb...)

2) Setup the ZABBIX database

    Follow the directions at :

  https://www.zabbix.com/documentation/${shortver}/manual/appendix/install/db_scripts

    The *.sql files it refers to are in ${prefix}/share/zabbix/scripts/
    ** NOTE THAT THESE ARE FOR YOUR SELECTED DATABASE VARIANT!!! **


3) Edit the sample .conf file ${prefix}/etc/zabbix${zver}/zabbix_server.conf
   (rename & omit .sample)

   Modify these variables at the very least:

    DBName=zabbix
    DBUser=zabbix
    DBPassword=<zabbix-mysql-password>
    DBSocket=<location for your active sql server socket>

4) Set zabbix_server to run at system boot (also starts it immediately):

    sudo port load zabbix${zver}

5) Read the fine manual at http://www.zabbix.com/documentation/

#### End ZABBIX${zver} local server installation section   ####
####                                                 ####

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! ZABBIX${zver} Server Version Upgrade process
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!  0) Be sure to use 'sudo port unload zabbixN' to stop the background
!!     server before deactivating zabbixN. (Whatever version you are running.)
!!
!!  1) BACK UP YOUR DATABASE
!!
!!  2) Create/edit ${prefix}/etc/zabbix${zver}/zabbix_server.conf
!!        zabbix_server.conf.sample is available for reference.
!!        There are new features to consider.
!!        ** NOTE conf dir is etc/zabbix${zver} **
!!
!!  3) 'sudo port load zabbix${zver}' after installing.
!!
!!  For complete upgrade directions, please see:
!!    http://www.zabbix.com/documentation/${shortver}/manual/installation/upgrade
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!  ALWAYS BACK UP YOUR DATABASE BEFORE UPGRADING (between unload/load)!  !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"
}
