#!/bin/sh

set -e

.  "$COINAGENT_PROVISIONING_DIR"/common/unix/DownloadURL.sh


install_telegraf_on_generic_unix () {

    telegraf_sha256_list="$COINAGENT_PROVISIONING_DIR"/common/shared/telegraf/telegraf_packages.sha256.txt

    # 1. Download and install ioping

    case $COINAGENT_OS_ID in

        # SLES 12/15 does not have ioping in its repositories, and this RPM works in all SUSE/OpenSUSE distros
        suse|sles|opensuse*)
            DownloadURL  \
                '' \
                http://download.opensuse.org/repositories/benchmark/SLE_15_SP1/x86_64/ioping-1.0-11.3.x86_64.rpm \
                72f7914ff55f6e55979095e6beab463f53913d8d  \
                ioping-1.0-11.3.x86_64.rpm
            sudo zypper -nq --no-gpg-checks install ./ioping-1.0-11.3.x86_64.rpm
            ;;
        # All other distros have "ioping" in their repositories
        *)
            $COINAGENT_PKG_INSTALL ioping
    esac

    # 2. Install custom ioping monitoring script

    sudo cp  "$COINAGENT_PROVISIONING_DIR"/common/shared/telegraf/ioping-telegraf.sh  /usr/local/bin/
    sudo chmod +x  /usr/local/bin/ioping-telegraf.sh
    
    # 3. Download and install telegraf

    [ x"$COINAGENT_OS"   = xmacos ] && os=darwin || os=linux
    [ x"$COINAGENT_ARCH" = xx86   ] && arch=i386 || arch=amd64
    package_filename=telegraf-1.12.1_${os}_${arch}.tar.gz
    package_sha256=$(sed -sn "s/$package_filename *//p" "$telegraf_sha256_list")

    DownloadURL  \
        http://local-file-server.intra.qt.io/telegraf/$package_filename  \
        https://dl.influxdata.com/telegraf/releases/$package_filename  \
        $package_sha256  \
        telegraf.tar.gz

    tar -xzf ./telegraf.tar.gz -C /tmp
    telegraf_binary=$(find /tmp/telegraf* -name telegraf | grep /bin/ | head -1)
    sudo cp "$telegraf_binary" /usr/local/bin/
    sudo chown root:root /usr/local/bin/telegraf
    sudo chmod 755       /usr/local/bin/telegraf
    rm -rf /tmp/telegraf*

    # 4. Edit config file with passwords
    "$COINAGENT_PROVISIONING_DIR"/common/unix/telegraf_password.sh
}