#! /bin/sh

if [ -z "${SKIP_NETDATA}" ] && NETDATA_STREAM=$(host -t SRV _netdata-stream._tcp | head -1) && NETDATA_REGISTRY=$(host -t SRV _netdata-registry._tcp | head -1) && NETDATA_CONFIG=$(host -t TXT netdata._autoconfig | head -1); then
echo "Setting up Netdata"
NETDATA_APIKEY=$(echo $NETDATA_CONFIG | awk '{ gsub(/"/, "", $4); match($4, "apikey="); print substr($4, RLENGTH + 1)}')
pkg install -y netdata
pkg install -y netdata-go
cat << EOF >/usr/local/etc/netdata/netdata.conf
# netdata configuration
#
# This file is a small subset of the full configuration which can be downloaded
# from http://localhost:19999/netdata.conf

# global netdata configuration

[global]
    history = 86400
    memory mode = none

[plugins]
    freebsd = yes

[web]
    mode = none
    respect do not track policy = yes
    disconnect idle clients after seconds = 3600
    bind to = 127.0.0.1
    web files owner = netdata
    web files group = netdata

[registry]
    enabled = no
    registry to announce = http://$(echo $NETDATA_REGISTRY | awk '{print $8}' | sed "s/\.$//" ):$(echo $NETDATA_REGISTRY | awk '{print $7}')

[health]
    enabled = no
EOF
cat << EOF >/usr/local/etc/netdata/stream.conf
[stream]
    enabled = yes 
    destination = $(echo $NETDATA_STREAM | awk '{print $8}' | sed "s/\.$//")
    api key = ${NETDATA_APIKEY}
EOF
service netdata enable
else
echo "Not setting up monitoring"
fi
