# @description This function adds Netdata to a pfSense environment. More specifically, it:
#
#     1. Enables the FreeBSD package repo
#     2. Installs Netdata system package dependencies
#     3. Configures Netdata to work with Netdata Cloud (if the `NETDATA_TOKEN` environment variable is appropriately assigned)
#     4. Starts the Netdata service
#
#     **Note:** In order for Netdata to start on reboot, the shell command feature of pfSense should be configured to
#     run `service netdata onestart` after reboots.
enableNetdata() {
    ### Enable FreeBSD package repo
    logg info 'Enabling FreeBSD package repo'
    FILE_PATH="/usr/local/etc/pkg/repos/pfSense.conf"
    TMP_FILE=$(mktemp)
    REPLACEMENT="FreeBSD: { enabled: yes }"
    echo "$REPLACEMENT" > "$TMP_FILE"
    tail -n +2 "$FILE_PATH" >> "$TMP_FILE"
    mv -f "$TMP_FILE" "$FILE_PATH"
    rm -f "$TMP_FILE"

    ### Install Netdata / dependencies
    logg info 'Installing Netdata system package dependencies'
    pkg update
    pkg install -y curl pkgconf bash e2fsprogs-libuuid libuv nano
    pkg install -y json-c-0.15_1
    pkg install -y py39-certifi-2023.5.7
    pkg install -y py39-asn1crypto
    pkg install -y py39-pycparser
    pkg install -y py39-cffi
    pkg install -y py39-six
    pkg install -y py39-cryptography
    pkg install -y py39-idna
    pkg install -y py39-openssl
    pkg install -y py39-pysocks
    pkg install -y py39-urllib3
    pkg install -y py39-yaml
    pkg install -y netdata

    ### Modify Netdata configuration
    if [ -n "$NETDATA_TOKEN" ]; then
        logg info 'Configuring Netdata to work with Netdata Cloud'
        # TODO: Add below to netdata.conf
        # bind to = 127.0.0.1 to bind to = 0.0.0.0
        cat <<EOF > /usr/local/etc/netdata/netdata.conf
[backend]
    enabled = yes
    data source = netdata
    destination = https://app.netdata.cloud
    api key = ${NETDATA_TOKEN}
EOF
    fi

    ### Start Netdata
    logg info 'Starting Netdata service'
    service netdata onestart
}
