#!/usr/bin/env bash
set -euo pipefail

if [ -f /etc/cmk-push-agent/cmk-push-agent.conf ]; then
    source /etc/cmk-push-agent/cmk-push-agent.conf

    echo "Downloading current checkmk agent from server $CMK_SERVER/$CMK_SITE"

    for dl in check_mk_agent check_mk_caching_agent; do
        echo "Getting file $dl"
        curl -s -o /tmp/$dl -k https://${CMK_SERVER}/${CMK_SITE}/check_mk/agents/${dl}.linux

        if head /tmp/$dl | grep Checkmk > /dev/null 2>&1; then
            chmod 750 /tmp/$dl
            echo "Copying $dl to /usr/bin"
            cp /tmp/$dl /usr/bin/$dl
        fi
        echo "Finished $dl update."
    done

    for dl in mk-job waitmax; do
        echo "Getting file $dl"
        curl -s -o /tmp/$dl -k https://${CMK_SERVER}/${CMK_SITE}/check_mk/agents/${dl}
        chmod 750 /tmp/$dl
        echo "Copying $dl to /usr/bin"
        cp /tmp/$dl /usr/bin/$dl
        echo "Finished $dl update."
    done

    if ! systemd-detect-virt > /dev/null 2>&1; then
        echo "Getting smart plugin"
        curl -s -o /tmp/smart https://${CMK_SERVER}/${CMK_SITE}/check_mk/agents/plugins/smart
        chmod 750 /tmp/smart
        echo "Copying smart plugin to /usr/lib/check_mk_agent/plugins"
        cp /tmp/smart /usr/lib/check_mk_agent/plugins/smart
        echo "Finished smart plugin update."
    fi

    echo "Refreshing plugins"
    /usr/bin/cmk-push-plugin-manager

else
    exit 0
fi