# -*- 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           github 1.0
PortGroup           java 1.0

# on version update, check gradle version, branches.json hash (see below)
github.setup        elastic elasticsearch 9.5.6 v
revision            0
set gradle_version  9.7.1
set branches_json_hash  bdf3da5aa2dc82bd771cc6b57c5b1cdfc8251d58

categories          databases java
supported_archs     arm64 x86_64
platforms           {darwin any}
license             AGPL-3
maintainers         @gerardsoleca openmaintainer
github.tarball_from archive

description         Free and Open Source, Distributed, RESTful Search Engine
long_description    Elasticsearch is a distributed search and analytics engine, \
                    scalable data store and vector database optimized for speed \
                    and relevance on production-scale workloads. Elasticsearch \
                    is the foundation of Elastic’s open Stack platform. Search \
                    in near real-time over massive datasets, perform vector searches, \
                    integrate with generative AI applications, and much more.

homepage            https://www.elastic.co/

depends_build-append    path:bin/git:git

# Required java version
# https://github.com/elastic/elasticsearch/blob/main/CONTRIBUTING.md
set java_version    21
set required_java   openjdk${java_version}-temurin
depends_lib-append  port:${required_java}
set java_home       ${prefix}/Library/Java/JavaVirtualMachines/jdk-${java_version}-eclipse-temurin.jdk/Contents/Home

# commands to determine necessary jdk version for main build and dependencies
# main build
# cd ${worksrcpath}
# cat build-tools-internal/src/main/resources/minimumCompilerVersion \
#     build-tools-internal/src/main/resources/minimumRuntimeVersion \
#     .ci/java-versions.properties
#
# dependencies; set JAVA_VERSION to main build version
# JAVA_VERSION=21; { find . -type d -name 'main[0-9][0-9]' \
#     -path '*/src/*' -not -path '*/build/*' 2>/dev/null \
#   | sed -E 's|.*/main([0-9]+)$|\1|'; \
#   grep -rnoE --include=*.gradle --include=*.kts --include=*.java \
#     --include=*.groovy \
#     '\b[Mm]ain(2[2-9]|3[0-9])\b|JavaLanguageVersion\.of\( *(2[2-9]|3[0-9])' . \
#     2>/dev/null | grep -vE '/build/|/src/(test|integTest)/' \
#   | sed -E 's/.*[^0-9]([0-9]+)$/\1/'; \
# } | sort -un | awk -v v="$JAVA_VERSION" '$1>v' | tr '\n' ' '; echo

# dependencies pinned to other jdk's
set jdk_homes       {}
lappend jdk_homes   ${java_home}
set jdk_versions    {22 23 25 26 27}
foreach v $jdk_versions {
    depends_build-append    port:openjdk${v}-temurin
    lappend jdk_homes       ${prefix}/Library/Java/JavaVirtualMachines/jdk-${v}-eclipse-temurin.jdk/Contents/Home
}

set main_distfile   ${distfiles}

# gradle
# https://github.com/elastic/elasticsearch/blob/main/gradle/wrapper/gradle-wrapper.properties
set gradle_distfile gradle-${gradle_version}-bin.zip
master_sites-append https://services.gradle.org/distributions/:gradle
distfiles-append    ${gradle_distfile}:gradle

# ${branches_json} for latest version, get hash (*different* from release) from:
# https://github.com/elastic/elasticsearch/commits/main/${branches_json}
set branches_json   branches.json
master_sites-append ${github.raw}/${branches_json_hash}/:branches_json
distfiles-append    ${branches_json}:branches_json

# give branches.json a hash-dependent filename to avoid update clashes
set branches_file   ${branches_json}-${branches_json_hash}
post-fetch {
    if {[file exists ${distpath}/${branches_json}]} {
        delete -force ${distpath}/${branches_file}
        move ${distpath}/${branches_json} ${distpath}/${branches_file}
    }
}
pre-checksum {
    set idx [lsearch -exact ${all_dist_files} ${branches_json}]
    if {${idx} >= 0} {
        set all_dist_files \
            [lreplace ${all_dist_files} ${idx} ${idx} ${branches_file}]
    }
}

checksums           ${main_distfile} \
                    rmd160  31440d6e667865097c395e5b326aa2bd60e980fb \
                    sha256  99fcf13fe030906be9866f528e01a0b08016dde34afefda7baf106c1176907c1 \
                    size    123125481 \
                    ${gradle_distfile} \
                    rmd160  57764b6e7436bf0e9f90c38f6afd7a8690b472e2 \
                    sha256  acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a \
                    size    151433392 \
                    ${branches_file} \
                    rmd160  12708fe190a6652ef0d0abffbcc48f83069ee1ed \
                    sha256  ff0f9622a91835d5617ca2856659ad364cf0cb54a7bb1bef9ed467e4fadbeb72 \
                    size    450

proc percent_encode {str} { 
    return [subst [regsub -all {[^a-zA-Z0-9/.~_-]} $str {%[format %02x [scan {&} %c]]}]]
}

# runtime java (not bundled); check that run time java is the same as build java:
# cat ${worksrcpath}/build-tools-internal/src/main/resources/minimumRuntimeVersion
set es_java_home    ${java_home}

if {${configure.build_arch} eq "arm64"} {
    set dist_dir    darwin-aarch64-tar
    set dist_suffix darwin-aarch64
} else {
    set dist_dir    darwin-tar
    set dist_suffix darwin-x86_64
}

extract.only        ${main_distfile}

# diff -Naurd -I '^ *#' ./elasticsearch-orig/gradle/wrapper/gradle-wrapper.properties ./elasticsearch-new/gradle/wrapper/gradle-wrapper.properties | sed -E -e 's/\.\/elasticsearch-(orig|new)\//\.\//' > patch-gradle-wrapper_properties.diff
patchfiles-append   patch-gradle-wrapper_properties.diff

# diff -Naurd -I '^ *#' ./elasticsearch-orig/distribution/archives/build.gradle ./elasticsearch-new/distribution/archives/build.gradle | sed -E -e 's/\.\/elasticsearch-(orig|new)\//\.\//' > patch-no-bundled-jdk.diff
patchfiles-append   patch-no-bundled-jdk.diff

post-patch {
    reinplace "s|@DISTPATH@|[percent_encode ${distpath}]|g" \
                    ${build.dir}/gradle/wrapper/gradle-wrapper.properties
    reinplace "s|@GRADLE_VERSION@|[percent_encode ${gradle_version}]|g" \
                    ${build.dir}/gradle/wrapper/gradle-wrapper.properties

    xinstall -d ${workpath}/gradle
    set fd [open ${workpath}/gradle/gradle.properties w]
    puts $fd "org.gradle.java.installations.auto-download=false"
    puts $fd "org.gradle.java.installations.paths=[join ${jdk_homes} ,]"
    close $fd
}

post-patch {
    copy          ${distpath}/${branches_file} \
                  ${worksrcpath}/${branches_json}
}

# tell gradle about the proxy, if any
post-patch {
    set props ""
    foreach {scheme var} {http http_proxy https https_proxy} {
        set val ""
        foreach envname [list $var [string toupper $var]] {
            if {[info exists env($envname)]} {
                set val $env($envname)
                break
            }
        }
        if {[regexp {^(?:[a-z]+://)?(?:[^@/]*@)?([^:/]+):([0-9]+)} $val -> host port]} {
            append props "systemProp.${scheme}.proxyHost=${host}\n"
            append props "systemProp.${scheme}.proxyPort=${port}\n"
        }
    }
    set fd [open ${workpath}/gradle/gradle.properties a]
    puts -nonewline $fd $props
    close $fd
}

# give the build a minimal .git so build_hash reports the real release commit
post-patch {
    set git_commit ""
    set peeled 0
    if {![catch {exec git ls-remote ${github.homepage} \
            refs/tags/${git.branch} refs/tags/${git.branch}^{}} ls_out]} {
        foreach ls_line [split $ls_out \n] {
            lassign [split $ls_line \t] rev ref
            if {[string match "*^\{\}" $ref]} {
                set git_commit $rev
                set peeled 1
            } elseif {!$peeled && $git_commit eq ""} {
                set git_commit $rev
            }
        }
    }

    if {[string length $git_commit] == 40} {
        xinstall -d ${worksrcpath}/.git
        set fd [open ${worksrcpath}/.git/HEAD w]
        puts $fd $git_commit
        close $fd
        set fd [open ${worksrcpath}/.git/config w]
        puts $fd "\[remote \"origin\"\]"
        puts $fd "\turl = ${git.url}"
        close $fd
        ui_msg "build_hash will be ${git_commit}"
    } else {
        ui_warn "Could not determine the git commit for ${git.branch}; build_hash will be \"unknown\""
    }
}

set elasticdir      ${prefix}/share/${name}
set confdir         ${prefix}/etc/${name}
set logdir          ${prefix}/var/log/${name}
set dbdir           ${prefix}/var/${name}
set user            ${name}
set group           ${user}

# Elasticsearch cannot run as root, so a dedicated user is required
add_users           ${user} group=${group} realname=Elasticsearch\ Server

use_configure       no

build.env-append    GRADLE_USER_HOME=${workpath}/gradle \
                    "JAVA_HOME=${java_home}"

build.cmd           ./gradlew --info --stacktrace
# https://github.com/elastic/elasticsearch/tree/main/distribution/archives
if {${configure.build_arch} eq "arm64"} {
    build.target    :distribution:archives:darwin-aarch64-tar:assemble
    set arch_name   aarch64
} else {
    build.target    :distribution:archives:darwin-tar:assemble
    set arch_name   x86_64
}

build.post_args     --no-daemon

# property name for branches.json
# grep -rn "BRANCHES_FILE_LOCATION_PROPERTY *=" "${worksrcpath}/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/info/GlobalBuildInfoPlugin.java"
build.post_args-append \
                    "-Porg.elasticsearch.build.branches-file-location=${worksrcpath}/${branches_json}"

destroot {
    set es_tarball [lindex [glob \
        ${worksrcpath}/distribution/archives/${dist_dir}/build/distributions/elasticsearch-*-${dist_suffix}.tar.gz] 0]

    xinstall -m 755 -o ${user} -g ${group} -d \
        ${destroot}${elasticdir} \
        ${destroot}${confdir} \
        ${destroot}${logdir} \
        ${destroot}${dbdir} \
        ${destroot}${prefix}/bin

    system -W ${worksrcpath} \
        "[findBinary tar ${portutil::autoconf::tar_command}] -xzf ${es_tarball} -C ${destroot}${elasticdir} --strip-components=1"

    # config lives in etc
    foreach f [glob ${destroot}${elasticdir}/config/*] {
        file rename $f ${destroot}${confdir}/[file tail $f]
    }
    file delete -force ${destroot}${elasticdir}/config

    # disable xpack.security on basic localhost install
    set fd [open ${destroot}${confdir}/elasticsearch.yml a]
    puts $fd "\n# MacPorts: local-only default, security disabled"
    puts $fd "xpack.security.enabled: false"
    close $fd

    # local configurable jvm.options
    xinstall -d ${destroot}${confdir}/jvm.options.d
    set fd [open ${destroot}${confdir}/jvm.options.d/heap.options.example w]
    puts $fd "# Rename to heap.options (and keep Xms equal to Xmx) to cap the heap:"
    puts $fd "# -Xms1g"
    puts $fd "# -Xmx1g"
    close $fd

    # The stock jvm.options writes to relative logs/ and data/ (the working
    # directory is ES_HOME, which is root-owned). Point them at var instead.
    file delete -force ${destroot}${elasticdir}/logs \
                       ${destroot}${elasticdir}/data \
                       ${destroot}${elasticdir}/plugins \
                       ${destroot}${elasticdir}/jdk.app
    ln -s ../../var/log/${name} ${destroot}${elasticdir}/logs
    ln -s ../../var/${name}     ${destroot}${elasticdir}/data

    # Wrappers set the config path and JDK, so bin/elasticsearch-env needs no patch
    foreach script [glob ${destroot}${elasticdir}/bin/elasticsearch*] {
        set tool [file tail $script]
        if {[string match *.jar $tool] || [string match elasticsearch-env* $tool]
            || $tool eq "elasticsearch-cli"} { continue }
        set wrapper ${destroot}${prefix}/bin/${tool}
        set fd [open $wrapper w]
        puts $fd "#!/bin/sh"
        puts $fd "export ES_PATH_CONF=\"\${ES_PATH_CONF:-${confdir}}\""
        puts $fd "export ES_JAVA_HOME=\"\${ES_JAVA_HOME:-${es_java_home}}\""
        puts $fd "exec ${elasticdir}/bin/${tool} \"\$@\""
        close $fd
        file attributes $wrapper -permissions 0755
    }
}

destroot.keepdirs-append ${destroot}${logdir} ${destroot}${dbdir}

post-activate {
    xinstall -d ${elasticdir}/plugins

    system "chown -R root:${group} ${elasticdir}"
    system "chown -R ${user}:${group} ${confdir}"
    system "chown -R ${user}:${group} ${logdir}"
    system "chown -R ${user}:${group} ${dbdir}"
}

notes "\
Elasticsearch ${github.version} runs on Java ${java_version},\
which is installed as a dependency.

Configuration lives in ${confdir}, data in ${dbdir} and logs in ${logdir}.
After editing any configuration file, restart the service:

    sudo port reload ${name}

SECURITY
This port ships with security turned off (xpack.security.enabled: false in\
${confdir}/elasticsearch.yml), and Elasticsearch listens on localhost only.\
Requests need no credentials:

    curl \"http://localhost:9200?pretty\"

Do not change network.host to a non-loopback address while security is off,\
because anyone who can reach the port could read and delete your data. To\
turn security on, delete that line from elasticsearch.yml, restart, and set\
a password for the built-in elastic user:

    sudo -u ${user} ${prefix}/bin/elasticsearch-reset-password -u elastic -i

After that, requests need credentials (curl -u elastic ...).

MEMORY (JVM OPTIONS)
By default Elasticsearch sizes its own heap, up to about half of the machine's\
memory. To set a fixed size, create a file ending in .options in\
${confdir}/jvm.options.d, for example:

    sudo mkdir -p ${confdir}/jvm.options.d
    printf -- '-Xms1g\\n-Xmx1g\\n' | sudo tee ${confdir}/jvm.options.d/heap.options

Keep -Xms and -Xmx equal, then restart the service. Prefer files in\
jvm.options.d over editing ${confdir}/jvm.options, so your settings are not\
overwritten when the port is upgraded.

To interact with Elasticsearch, start with commands like:

# default Elasticsearch response
curl -XGET \"http://localhost:9200?pretty\"

# create and configure a new index
curl -XPUT \"http://localhost:9200/my_first_index\" \\
  -H 'Content-Type: application/json' -d'
{
    \"settings\" : {
        \"index\" : {
            \"number_of_shards\" : 5,
            \"number_of_replicas\" : 2
        }
    }
}
'

# examine cluster health, shard disk usage and status
curl -XGET \"http://localhost:9200/_cluster/health?pretty\"
curl -XGET \"http://localhost:9200/_cat/shards?v\"

# irreversibly delete all data in /my_first_index
curl -XDELETE \"http://localhost:9200/my_first_index\"

Each Elasticsearch shard is a Lucene index; aim for 10-50 GB per shard.
"

startupitem.create      yes
startupitem.logfile     ${logdir}/daemon.log
startupitem.executable  sudo -u elasticsearch ${prefix}/bin/${name}
