#!/bin/bash
#
#Server-Manager: o_monitoring (Manages all monitoring matters) [Power: 755]
#
#Version: 3.4.6
#Date:    2026.03.02
#Unix:    Debian 21
#Author:  P.Klapp
#Company: Omoti UG (haftungsbeschränkt)
#Website: https://omoti.de
#
#Path:    /Commands/


#Version
    version=$(sed -n '5p' ${0})
    version=${version#*\ }

#Temporary file
    tmp="/srv/omoti/tmp/o_monitoring.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).tmp"

#Parameters
    #missing parameter
        if [[ -z ${1} ]]
        then
            echo -e '\033[33mMissing parameter!\033[0m Please use -h for help.'
            exit 1
        fi

    while getopts ':hinruv' option
    do
        case ${option} in
            h)  #help
                echo ''
                echo 'Usage: o_monitoring OPTION...'
                echo "o_monitoring (v${version}) Manages all monitoring matters"
                echo ''
                echo 'Options:'
                echo '-h            Display this help and exit'
                echo '-i            Installs the checkmk agent'
                echo '-n            Command is executed on an internal network'
                echo '-r            Reinstalls the checkmk agent'
                echo '-u            Updates the checkmk agent'
                echo '-v            Shows the version of the checkmk agend'
                echo ''
                echo 'Further documentation can be found in the Omoti Wiki'
                echo 'https://gitlab.omoti.work/omoti/Server-Manager/-/wikis/home'
                echo ''
                exit 0
            ;;

            i)  #install
                task='install'
            ;;

            n)  #network
                internal='true'
            ;;

            r)  #reinstall
                task='reinstall'
            ;;

            u)  #update
                task='update'
            ;;

            v)  #version
                task='version'
            ;;

            \?) #invalid option
                echo -e '\033[33mInvalid option!\033[0m Please use -h for help.'
                exit 1
            ;;

            :)  #missing argument
                echo -e '\033[33mMissing argument!\033[0m Please use -h for help.'
                exit 1
            ;;
        esac
    done
    unset option

#Functions
    GetAgentVersion () {
        cat /usr/bin/check_mk_agent | grep 'Version: ' | sed 's/Version: //' | head -n 1
    }

    VersionAtLeast () {
        currentVersion=${1}
        requiredVersion=${2}

        if [[ -z ${currentVersion} ]] || [[ -z ${requiredVersion} ]]
        then
            return 1
        fi

        if [[ $(printf '%s\n%s\n' "${requiredVersion}" "${currentVersion}" | sort -V | head -n 1) == "${requiredVersion}" ]]
        then
            return 0
        fi

        return 1
    }

    SetDownloadMode () {
        downloadMode='legacy'
        omotiServerVersion=''

        if ! command -v omoti-server &> /dev/null
        then
            return
        fi

        if ! [[ -f /etc/omoti/credentials.json ]]
        then
            return
        fi

        omotiServerVersion=$(omoti-server -V 2> /dev/null)
        omotiServerVersion=${omotiServerVersion##* }

        if VersionAtLeast "${omotiServerVersion}" '0.7.0'
        then
            downloadMode='omoti-server'
        fi
    }

    DownloadFile () {
        source=${1}
        targetFile=${source##*/}
        downloadPath="/tmp/o_monitoring.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).${targetFile}"

        #check parameter
            if [[ -z ${source} ]]
            then
                echo -e '\033[31mUnknown error!\033[0m Please check the log.'
                o_log -e 'Function DownloadFile: Missing parameter'
                exit 1
            fi

        if [[ ${downloadMode} == 'omoti-server' ]]
        then
            if ! omoti-server download --url "${source}" --path "${downloadPath}" --login &>> /srv/omoti/tmp/setup.log
            then
                echo -e "\033[31mFailed to download ${targetFile}\033[0m"
                o_log -e "Failed to download ${targetFile} via omoti-server"
                exit 1
            fi

            if ! [[ -f ${downloadPath} ]]
            then
                echo -e "\033[31mFailed to download ${targetFile}\033[0m"
                o_log -e "Downloaded file ${targetFile} is missing after omoti-server download"
                exit 1
            fi

            if ! mv "${downloadPath}" "${targetFile}"
            then
                echo -e "\033[31mFailed to move ${targetFile}\033[0m"
                o_log -e "Failed to move downloaded file ${targetFile} from /tmp"
                exit 1
            fi

        else
            o_download -a "${source}"
        fi
    }

    InstallPlugin () {
        plugin=${1}

        #check parameter
            if [[ -z ${plugin} ]]
            then
                echo -e '\033[31mUnknown error!\033[0m Please check the log.'
                o_log -e 'Funktion InstallPlugin: Missing parameter'
            fi

        DownloadFile "https://mgmt.omoti.de/Parts/Checkmk/Extensions/${plugin}"
        mv ${plugin} /usr/lib/check_mk_agent/plugins/
        chmod 700 /usr/lib/check_mk_agent/plugins/${plugin}

        #check file
            if [[ -f /usr/lib/check_mk_agent/plugins/${plugin} ]]
            then
                echo -e "\033[32mCheckmk plugin ${plugin} was installed\033[0m"
                o_log -i "Checkmk plugin ${plugin} was installed"

            else
                echo -e "\033[31mFailed to install the checkmk plugin ${plugin}\033[0m"
                o_log -e "Failed to install the checkmk plugin ${plugin}"
            fi
    }

    InstallLocal () {
        plugin=${1}

        #check parameter
            if [[ -z ${plugin} ]]
            then
                echo -e '\033[31mUnknown error!\033[0m Please check the log.'
                o_log -e 'Funktion InstallLocal: Missing parameter'
            fi

        DownloadFile "https://mgmt.omoti.de/Parts/Checkmk/Extensions/${plugin}"
        mv ${plugin} /usr/lib/check_mk_agent/local/
        chmod 700 /usr/lib/check_mk_agent/local/${plugin}

        #check file
            if [[ -f /usr/lib/check_mk_agent/local/${plugin} ]]
            then
                echo -e "\033[32mCheckmk local check ${plugin} was installed\033[0m"
                o_log -i "Checkmk local check ${plugin} was installed"

            else
                echo -e "\033[31mFailed to install the checkmk local check ${plugin}\033[0m"
                o_log -e "Failed to install the checkmk local check ${plugin}"
            fi
    }

#Dependencies
    #task
        if [[ -z ${task} ]]
        then
            echo -e '\033[33mInvalid option!\033[0m Please use -h for help.'
                exit 1
        fi

    #agent
        #not existing
            if [[ ${task} == 'install' ]] && [[ -f /usr/bin/check_mk_agent ]]
            then
                echo -e '\033[33mThe agent is already installed\033[0m'
                echo -e 'Please use \033[36m-u \033[0mto update the angent'
                exit 1
            fi

        #existing
            if ([[ ${task} == 'reinstall' ]] || [[ ${task} == 'update' ]] || [[ ${task} == 'version' ]]) && ! [[ -f /usr/bin/check_mk_agent ]]
            then
                echo -e '\033[33mNo installed agent found\033[0m'
                echo -e 'Please use \033[36m-i \033[0mto install the agent'
                exit 1
            fi

    #install/reinstall/update
        if [[ ${task} == 'install' ]] || [[ ${task} == 'reinstall' ]] || [[ ${task} == 'update' ]]
        then
            #user
                if [[ ${USER} != 'root' ]]
                then
                    echo -e '\033[33mThe selected parameters requests root rights!\033[0m'
                    echo 'Please run the command as root or with sudo.'
                    exit 1
                fi

            #network (check if the command is executed on an internal network without parameter -n)
                if [[ -z ${internal} ]] && [[ ${task} != 'update' ]]
                then
                    ipv4=$(hostname -I)
                    ipv4=${ipv4%%\.*}

                    if [[ ${ipv4} == '10' ]] || [[ ${ipv4} == '172' ]] || [[ ${ipv4} == '192' ]]
                    then
                        echo -e '\033[33mInternal network detected!\033[0m'
                        read -p 'Proceed with installation for a public network (y/n) [n]: ' question

                        if [[ -z ${question} ]] || ([[ ${question} != 'y' ]] && [[ ${question} != 'yes' ]])
                        then
                            echo -e '\033[33mInstallation aborted!\033[0m'
                            exit 1
                        fi
                    fi
                fi

            #required software
                #xinetd
                    if ! [[ $(which xinetd) ]]
                    then
                        echo 'Install missing software xinetd ...'
                        apt install -y xinetd &>> /srv/omoti/tmp/setup.log
                    fi
        fi

#Variables
    agent='check-mk-agent_2.4.0p21-1_all.deb'
    cron_entry='*/20 * * * * root echo "$(date +'\''\%s'\'')" > /srv/omoti/tmp/cron_heartbeat.tmp'
    #downloadMode   -> Functions/SetDownloadMode
    #downloadPath   -> Functions/DownloadFile
    #internal       -> Parameters
    #ipv4           -> Dependencies
    #mysql          -> Main/reinstall
    #newVersion     -> Main/update
    #oldVersion     -> Main/update
    #omotiServerVersion -> Functions/SetDownloadMode
    #plugin         -> Functions
    #question       -> Dependencies
    #source         -> Functions/DownloadFile
    #task           -> Parameters
    #targetFile     -> Functions/DownloadFile
    #tmp            -> Temporary file
    #version        -> Version
    xinetdConfig='/etc/check_mk/xinetd-service-template.cfg'

#Preparation
    SetDownloadMode

#Main
    #install
        if [[ ${task} == 'install' ]]
        then
            DownloadFile "https://mgmt.omoti.de/Parts/Checkmk/${agent}"
            gdebi --n ${agent} &>> /srv/omoti/tmp/setup.log
            rm ${agent}

            #controll
                if [[ -f /usr/bin/check_mk_agent ]]
                then
                    echo -e '\033[32mCheckmk agent was installed\033[0m'
                    o_log -i 'Checkmk agent was installed'

                else
                    echo -e "\033[31mFailed to install the checkmk agent\033[0m"
                    o_log -e 'Failed to install the checkmk agent'
                    exit 1
                fi

            #config
                #ssh
                    sed -i 's/PermitRootLogin no/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
                    service sshd restart

                    if ! [[ -d /root/.ssh/ ]]
                    then
                        mkdir -p /root/.ssh/
                        chmod 700 /root/.ssh/
                    fi

                    DownloadFile 'https://mgmt.omoti.de/Parts/Checkmk/authorized_keys'
                    if [[ -f /root/.ssh/authorized_keys ]]
                    then
                        cat authorized_keys >> /root/.ssh/authorized_keys

                    else
                        mv authorized_keys /root/.ssh/
                        chmod 600 /root/.ssh/authorized_keys
                    fi

                #xinetd
                    if [[ -f ${xinetdConfig} ]]
                    then
                        sed -i -e $(sed -n '/disable/=' ${xinetdConfig})c'\ \ \ \ disable = yes' ${xinetdConfig}
                    fi

                #filestats
                    DownloadFile 'https://mgmt.omoti.de/Parts/Checkmk/Extensions/filestats.cfg'
                    mv filestats.cfg /etc/check_mk/

            #local checks
                InstallLocal 'omoti_log'
                InstallLocal 'omoti_log.sh'
                InstallLocal 'omoti_dns.sh'

                if ! [[ -d /usr/lib/check_mk_agent/local/3600/ ]]
                then
                    mkdir /usr/lib/check_mk_agent/local/3600/
                fi

                mv /usr/lib/check_mk_agent/local/omoti_dns.sh /usr/lib/check_mk_agent/local/3600/

            #plugins
                InstallPlugin 'mk_filestats.py'
                InstallPlugin 'mk_iptables'
                InstallPlugin 'mk_sshd_config'

                if ! [[ -d /usr/lib/check_mk_agent/plugins/3600/ ]]
                then
                    mkdir /usr/lib/check_mk_agent/plugins/3600/
                fi

                #cron heartbeat
                    if ! grep -q "cron_heartbeat" /etc/crontab
                    then
                        echo "${cron_entry}" >> /etc/crontab
                    fi

                #network: public
                    if [[ -z ${internal} ]]
                    then
                        InstallPlugin 'omoti_speedtest'
                        mv /usr/lib/check_mk_agent/plugins/omoti_speedtest /usr/lib/check_mk_agent/plugins/3600/

                        echo "$(date +'%S') */1 * * * root /srv/omoti/scripts/speedtest.sh" >> /etc/crontab
                        /srv/omoti/scripts/speedtest.sh &>> /srv/omoti/tmp/setup.log
                        echo 'Setup of the checkmk plugin omoti_speedtest completed'
                    fi
        fi

    #reinstall
        if [[ ${task} == 'reinstall' ]]
        then
            #save mysql plugin configuration
                if [[ -f /etc/check_mk/mysql.cfg ]]
                then
                    mv /etc/check_mk/mysql.cfg ${tmp}
                    mysql='true'
                fi

            #delete all checkmk files
                rm /usr/bin/check_mk_agent
                rm -r /etc/check_mk/ /usr/lib/check_mk_agent/

            #delete ssh key
                sed -i '/check_mk_agent/d' /root/.ssh/authorized_keys

            #delete cronjob
                sed -i '/speedtest.sh/d' /etc/crontab

            if [[ ${internal} ]]
            then
                o_monitoring -i -n

            else
                o_monitoring -i
            fi

            #restore mysql plugin
                if [[ ${mysql} ]]
                then
                    mv ${tmp} /etc/check_mk/mysql.cfg
                    chmod 400 /etc/check_mk/mysql.cfg
                    InstallPlugin 'mk_mysql'
                    mkdir -p /usr/lib/check_mk_agent/plugins/300/
                    mv /usr/lib/check_mk_agent/plugins/mk_mysql /usr/lib/check_mk_agent/plugins/300/
                fi
        fi

    #update
        if [[ ${task} == 'update' ]]
        then
            #update agent
                oldVersion=$(GetAgentVersion)
                newVersion=${agent#*_}
                newVersion=${newVersion%-*}

                if [[ ${oldVersion} != ${newVersion} ]]
                then
                    DownloadFile "https://mgmt.omoti.de/Parts/Checkmk/${agent}"
                    gdebi --n ${agent} >> /srv/omoti/tmp/setup.log
                    rm ${agent}

                    echo "Checkmk agent was updated from ${oldVersion} to ${newVersion}."
                    o_log -i "Checkmk agent was updated from ${oldVersion} to ${newVersion}."
                fi

            #update checkmk plugins
                #mk_filestats.py
                    if [[ $(cat /usr/lib/check_mk_agent/plugins/mk_filestats.py | grep '__version__' | sed 's/__version__ = //' | sed 's/"//g') != ${newVersion} ]]
                    then
                        InstallPlugin 'mk_filestats.py'
                    fi

                #mk_iptables
                    if [[ $(cat /usr/lib/check_mk_agent/plugins/mk_iptables | grep 'CMK_VERSION' | sed 's/CMK_VERSION=//' | sed 's/"//g') != ${newVersion} ]]
                    then
                        InstallPlugin 'mk_iptables'
                    fi

                #mk_mysql
                    if [[ -f /usr/lib/check_mk_agent/plugins/300/mk_mysql ]] && [[ $(cat /usr/lib/check_mk_agent/plugins/300/mk_mysql | grep 'CMK_VERSION' | sed 's/CMK_VERSION=//' | sed 's/"//g') != ${newVersion} ]]
                    then
                        InstallPlugin 'mk_mysql'
                        mkdir -p /usr/lib/check_mk_agent/plugins/300/
                        mv /usr/lib/check_mk_agent/plugins/mk_mysql /usr/lib/check_mk_agent/plugins/300/
                    fi

                #mk_sshd_config
                    if [[ $(cat /usr/lib/check_mk_agent/plugins/mk_sshd_config | grep 'CMK_VERSION' | sed 's/CMK_VERSION=//' | sed 's/"//g') != ${newVersion} ]]
                    then
                        InstallPlugin 'mk_sshd_config'
                    fi

            #cron heartbeat
                if ! grep -q "cron_heartbeat" /etc/crontab
                then
                    echo "${cron_entry}" >> /etc/crontab
                fi
        fi

    #version
        if [[ ${task} == 'version' ]]
        then
            echo -e "Checkmk agent version:\033[36m $(GetAgentVersion)\033[0m"
            echo -e "Command version:      \033[36m ${version}\033[0m"
        fi
