#!/bin/bash
#
#Server-Manager: o_update (System Command: updates the system) [Power: 700]
#
#Version: 1.15.1
#Date:    2025.05.10
#Unix:    Debian 11
#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_update.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).tmp"

#Parameters
    cycles=${1}

#Functions
    UpdateOmoti () {    #Update management scripts
        #Parameters
            uo_path=${1}

        #Dependencies
            #parameters
                if [[ -z ${uo_path} ]]; then
                    echo -e "\033[31mError! ${uo_path}\033[0m"
                    exit 0
                fi

            #access
                #user
                    uo_dataUser=$(sed -n "$(sed -n '/-user/=' /srv/omoti/keys/access/data.cfg)p;" /srv/omoti/keys/access/data.cfg)
                    uo_dataUser=${uo_dataUser#*=}

                #token
                    uo_dataToken=$(sed -n "$(sed -n '/-token/=' /srv/omoti/keys/access/data.cfg)p" /srv/omoti/keys/access/data.cfg)
                    uo_dataToken=${uo_dataToken#*=}

                #controll
                    if [[ -z ${uo_dataUser} ]] || [[ -z ${uo_dataToken} ]]; then
                        echo -e "\033[31mError! No access data\033[0m"
                        exit 0
                    fi

        #Variables
            #uo_dataDir         -> Main/file info/data dir
            uo_dataDomain='https://mgmt.omoti.de'
            #uo_dataToken       -> Dependencies/access/token
            #uo_dataUser        -> Dependencies/access/user
            #uo_dataVersion     -> Main/data version
            uo_file=${uo_path##*/}
            #uo_localVersion    -> Main/file info/local version
            #uo_newVersion      -> Main/new version
            #uo_path            -> Parameters
            #uo_power           -> Main/file info/power
            uo_version='1.4.6'

        #Main
            #file info
                #data dir
                    if [[ -f ${uo_path} ]]; then
                        uo_dataDir=$(sed -n '12p' ${uo_path})
                        uo_dataDir="/${uo_dataDir#*\ /}"
                    else
                        uo_dataDir='/Commands/'
                    fi

                #local version
                    if [[ -f ${uo_path} ]]; then
                        uo_localVersion=$(sed -n '5p' ${uo_path})
                        uo_localVersion=${uo_localVersion#*\ }
                    fi

                    uo_localVersion=${uo_localVersion:='0.0.0'}

                #power
                    if [[ -f ${uo_path} ]]; then
                        uo_power=$(sed -n '3p' ${uo_path})
                        uo_power=${uo_power#*Power:\ }
                        uo_power=${uo_power%]*}
                    fi

                    uo_power=${uo_power:='700'}


            #data version
                uo_dataVersion=$(curl --user ${uo_dataUser}:${uo_dataToken} ${uo_dataDomain}${uo_dataDir}${uo_file} 2> /dev/null | sed -n '5p')
                uo_dataVersion=${uo_dataVersion#*\ }

                if [[ $(echo ${uo_dataVersion} | grep meta) ]]; then
                    unset uo_dataVersion
                fi

                uo_dataVersion=${uo_dataVersion:='0.0.0'}

            #update
                if [[ ${uo_dataVersion} != '0.0.0' ]] && [[ ${uo_dataVersion} != ${uo_localVersion} ]]; then
                    o_download -a "${uo_dataDomain}${uo_dataDir}${uo_file}"

                    if [[ -f ${uo_file} ]]; then
                        rm ${uo_path}
                        mv ${uo_file} ${uo_path}
                        chmod ${uo_power} ${uo_path}
                    fi
                fi

            #new version
                if [[ -f ${uo_path} ]]; then
                    uo_newVersion=$(sed -n '5p' ${uo_path})
                    uo_newVersion=${uo_newVersion#*\ }
                fi

                uo_newVersion=${uo_newVersion:='0.0.0'}

            #controll
                if [[ ${uo_dataVersion} == '0.0.0' ]]; then
                    echo -e "\033[31mError! No file available for update\033[0m"
                    o_log -e "No file available for update (${uo_path})"

                elif [[ ${uo_newVersion} == '0.0.0' ]]; then
                    echo -e "\033[31mCritical! Update failed, no new file\033[0m"
                    o_log -c "Update failed, no new file (${uo_path})"

                elif [[ ${uo_localVersion} != ${uo_dataVersion} ]] && [[ ${uo_localVersion} == ${uo_newVersion} ]]; then
                    echo -e "\033[33mWarning! Update faild\033[0m"
                    o_log -w "Update faild (${uo_path})"

                elif [[ ${uo_localVersion} != ${uo_dataVersion} ]] && [[ ${uo_dataVersion} == ${uo_newVersion} ]]; then
                    echo -e "\033[32m${uo_path} was successfully updated\033[0m"
                    o_log -i "${uo_path} was updated from ${uo_localVersion} to ${uo_newVersion}"

                elif [[ ${uo_localVersion} == ${uo_dataVersion} ]]; then
                    :
                else
                    echo -e "\033[31mCritical! Update failed without reason\033[0m"
                    o_log -c "Update failed without reason (${uo_path}|${uo_localVersion}|${uo_dataVersion}|${uo_newVersion})"
                fi

            unset uo_dataDir uo_dataDomain uo_dataToken uo_dataUser uo_dataVersion uo_file uo_localVersion uo_newVersion uo_path uo_power uo_version
    }

#Dependencies
    #omoti-server
        if [[ $(which omoti-server) ]]
        then
            omoti-server update
            omoti-server update --omoti
            exit 0
        fi

    #parameters
        cycles=${cycles:='1'}
        if ! [[ `echo "${cycles}" | grep -E ^[[:digit:]]+$` ]]; then
            cycles='1'
        fi

#Variables
    #access             -> Main/delete tmp-files/analyse mysql log
    #adjusterVersion    -> Main/adjuster
    counter='0'
    #cycles             -> Parameters
    #delete             -> Main/delete tmp-files
    #files              -> Main
    i='0'
    ipv0=$(hostname -I)
    ipv4=${ipv0%%\ *}
    speedtest='/srv/omoti/log/speedtest.log'
    #tmp                -> Temporary file
    #version            -> Version

#Main
    cd

    #update system
        while [[ ${cycles} != '0' ]]
        do
            apt update && apt upgrade -y
            apt --fix-broken install -y
            apt autoremove -y
            ((cycles--))

            o_log -i 'System was updated'
        done

    #update commands
        #/bin/
            IFS=$'\n' files=($(ls /bin/ | grep '^o_'))
            while [[ ${i} != ${#files[@]} ]]
            do
                UpdateOmoti "/bin/${files[${i}]}"
                ((i++))
            done

            if [[ -f /bin/ack_log ]]
            then
                UpdateOmoti "/bin/ack_log"
                ((i++))
            fi

            counter=$((counter + i))
            i='0'
            unset files

        #/sbin/
            IFS=$'\n' files=($(ls /sbin/ | grep '^o_'))
            while [[ ${i} != ${#files[@]} ]]
            do
                UpdateOmoti "/sbin/${files[${i}]}"
                ((i++))
            done

            counter=$((counter + i))
            i='0'
            unset files

        #o_log -d "${counter} commands detected"
        counter='0'

    #missing commands
        if [[ -f /etc/omoti/omoti.cfg ]]
        then
            #/bin/
                files=$(sed -n "$(sed -n '/-bin/=' /etc/omoti/omoti.cfg)p" /etc/omoti/omoti.cfg)
                files=${files#*=}
                IFS=$', ' files=(${files})

                while [[ ${i} != ${#files[@]} ]]
                do
                    if ! [[ -f /bin/${files[${i}]} ]]
                    then
                        UpdateOmoti "/bin/${files[${i}]}"
                        chmod 755 /bin/${files[${i}]}
                        ((counter++))
                    fi
                    ((i++))
                done

                i='0'
                unset files

            #/sbin/
                files=$(sed -n "$(sed -n '/-sbin/=' /etc/omoti/omoti.cfg)p" /etc/omoti/omoti.cfg)
                files=${files#*=}
                IFS=$', ' files=(${files})

                while [[ ${i} != ${#files[@]} ]]
                do
                    if ! [[ -f /sbin/${files[${i}]} ]]
                    then
                        UpdateOmoti "/sbin/${files[${i}]}"
                        chmod 755 /sbin/${files[${i}]}
                        ((counter++))
                    fi
                    ((i++))
                done

                i='0'
                unset files

            if [[ ${counter} != '0' ]]; then
                o_log -i "${counter} commands were missing"
                counter='0'
            fi
        fi

    #update scripts
        IFS=$'\n' files=($(ls /srv/omoti/scripts/))
        while [[ ${i} != ${#files[@]} ]]
        do
            if [[ ${files[${i}]} == 'fah.info' ]]
            then
                o_log -i "Exception detected (${files[${i}]})"
            else
                UpdateOmoti "/srv/omoti/scripts/${files[${i}]}"
            fi
            ((i++))
        done

        counter=$((counter + i))
        i='0'
        unset files

        if [[ ${counter} != '0' ]]; then
            #o_log -d "${counter} scripts detected"
            counter='0'
        fi

    #update other
        #checkmk
            #filestats
                if [[ -f /etc/check_mk/filestats.cfg ]]
                then
                    UpdateOmoti /etc/check_mk/filestats.cfg
                fi

            #omoti_log
                if [[ -f /usr/lib/check_mk_agent/local/omoti_log ]]
                then
                    UpdateOmoti /usr/lib/check_mk_agent/local/omoti_log
                fi

            #omoti_dns
                if [[ -f /usr/lib/check_mk_agent/local/3600/omoti_dns.sh ]]
                then
                    UpdateOmoti /usr/lib/check_mk_agent/local/3600/omoti_dns.sh
                fi

            #omoti_speedtest
                if [[ -f /usr/lib/check_mk_agent/plugins/3600/omoti_speedtest ]]
                then
                    UpdateOmoti /usr/lib/check_mk_agent/plugins/3600/omoti_speedtest
                fi

                #checkmk server
                    if [[ -f /omd/sites/main/local/lib/python3/cmk_addons/plugins/speedtest/agent_based/speedtest.py ]]; then
                        UpdateOmoti /omd/sites/main/local/lib/python3/cmk_addons/plugins/speedtest/agent_based/speedtest.py
                        chown main:main /omd/sites/main/local/lib/python3/cmk_addons/plugins/speedtest/agent_based/speedtest.py
                    fi

                    if [[ -f /omd/sites/main/local/share/check_mk/web/plugins/wato/omoti_speed_test_parameters.py ]]; then
                        UpdateOmoti /omd/sites/main/local/share/check_mk/web/plugins/wato/omoti_speed_test_parameters.py
                        chown main:main /omd/sites/main/local/share/check_mk/web/plugins/wato/omoti_speed_test_parameters.py
                    fi

            #notifications
                #gitlab_alert
                    if [[ -f /omd/sites/main/local/share/check_mk/notifications/gitlab_alert.sh ]]; then
                        UpdateOmoti /omd/sites/main/local/share/check_mk/notifications/gitlab_alert.sh
                    fi

        #customers
            if [[ -f /srv/omoti/scripts/updateUser.sh ]]; then
                /srv/omoti/scripts/updateUser.sh
            fi

    #delete tmp-files
        IFS=$'\n' files=($(ls --full-time /srv/omoti/tmp/ | grep -v $(date +'%Y-%m-%d')))
        while [[ ${i} != ${#files[@]} ]]; do
            delete="${files[${i}]}"
            delete=${delete#*+0000\ }

            if [[ -f /srv/omoti/tmp/${delete} ]]; then
                rm /srv/omoti/tmp/${delete}
                ((counter++))

            elif [[ -d /srv/omoti/tmp/${delete} ]]; then
                rm -r /srv/omoti/tmp/${delete}
                ((counter++))
            fi
            ((i++))
        done

        i='0'
        unset files

        if [[ ${counter} != '0' ]]; then
            o_log -i "${counter} tmp-files deleted"
            counter='0'
        fi

    #analyse mysql log
        if [[ -f /var/log/mysql/mysql.log ]]
        then
            access="$(cat /var/log/mysql/mysql.log | grep 'Access denied')"
            if [[ ${access} ]]
            then
                cat /var/log/mysql/mysql.log | grep 'Access denied' >> /srv/omoti/log/mysql.log
                o_log -w 'Unauthorised access detected'

            #else
            #    o_log -d "1: $(wc -l /var/log/mysql/mysql-slow.log)"
            #    sed -i '1,$d' /var/log/mysql/mysql-slow.log
            #    o_log -d "1: $(wc -l /var/log/mysql/mysql-slow.log)"
            fi

            #counter=$(wc -l /var/log/mysql/mysql.log)
            #counter=${counter%%\ *}
            #o_log -d "counter: ${counter}"
            #o_log -d "1: $(wc -l /var/log/mysql/mysql.log)"

            #if (( ${counter} > 10000 ))
            #then
            #    counter=$((counter - 10000))
            #    sed -i "1,${counter}d" /var/log/mysql/mysql.log
            #fi

            #counter='0'
            #o_log -d "2: $(wc -l /var/log/mysql/mysql.log)"

            awk -v date_lim="$(date -d "1 month ago" "+%Y-%m-%d")" 'BEGIN { FS = " "; } { if ($1 >= date_lim) print $0; }' /var/log/mysql/mysql.log > /var/log/mysql/mysql.log.tmp
            mv /var/log/mysql/mysql.log.tmp /var/log/mysql/mysql.log
            systemctl restart mysql
        fi

    #adjuster
        if [[ -f /srv/omoti/scripts/adjuster.sh ]]; then
            if [[ $(sed -n '15p' /srv/omoti/scripts/adjuster.sh) == 'true' ]]; then
                adjusterVersion=$(sed -n '5p' /srv/omoti/scripts/adjuster.sh)
                adjusterVersion=${adjusterVersion#*\ }

                o_log -i 'Adjuster was executed'
                /srv/omoti/scripts/adjuster.sh
            fi
        else
            o_download -a 'https://mgmt.omoti.de/Parts/Manager/adjuster.sh'
            mv adjuster.sh /srv/omoti/scripts/
            chmod 700 /srv/omoti/scripts/adjuster.sh
        fi

    #speedtest
        if [[ -f ${speedtest} ]]
        then
            tail -n 50 ${speedtest} > ${tmp}
            cat ${tmp} > ${speedtest}
        fi

    #save firewall
        iptables-save > /etc/iptables/rules.v4
        ip6tables-save > /etc/iptables/rules.v6
