#!/bin/bash
#
#Server-Manager: o_log (System Command: Writes text to the log) [Power: 755]
#
#Version: 2.6.11
#Date:    2025.03.29
#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_log.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).tmp"

#Parameters
    para_1=${1}
    para_2=${2}
    para_3=${3}

#Functions
    NewLog() {  #create a new log file
        #Parameters
        #Dependencies
            #caller script
                if [[ -z ${debugLog} ]] || [[ -z ${debugOld} ]] || [[ -z ${logFile} ]] || [[ -z ${logOld} ]] || [[ -z ${option} ]] || [[ -z ${version} ]]; then
                    echo -e "\033[31mError caller script data\033[0m"
                    exit 0
                fi

        #Variables
            #debugLog       -> Dependencies/caller script
            #debugOld       -> Dependencies/caller script
            #logFile        -> Dependencies/caller script
            #logOld         -> Dependencies/caller script
            #nl_dateOld     -> Main/old log
            #nl_nameOld     -> Main/old log
            nl_version='2.4.1'
            #option         -> Dependencies/caller script
            #version        -> Dependencies/caller script

        #Main
            #old log
                #debug log
                    if [[ -f ${debugLog} ]]; then
                        nl_dateOld=$(sed -n '3p' ${debugLog})

                        if [[ ${nl_dateOld} != $(date +'%Y-%m-%d') ]]; then
                            nl_nameOld="omoti-debug_$(hostname)_${nl_dateOld}.log"
                            mv ${debugLog} ${nl_nameOld}

                            if [[ -f ${debugOld} ]]; then
                                tar -rf ${debugOld} ${nl_nameOld}
                            else
                                tar -cf ${debugOld} ${nl_nameOld}
                                chmod 666 ${debugOld}
                            fi

                            rm ${nl_nameOld}
                        fi
                    fi

                #log
                    if [[ -f ${logFile} ]]; then
                        nl_dateOld=$(sed -n '3p' ${logFile})

                        if [[ ${nl_dateOld} != $(date +'%Y-%m-%d') ]]; then
                            nl_nameOld="omoti-log_$(hostname)_${nl_dateOld}.log"
                            mv ${logFile} ${nl_nameOld}

                            if [[ -f ${logOld} ]]; then
                                tar -rf ${logOld} ${nl_nameOld}
                            else
                                tar -cf ${logOld} ${nl_nameOld}
                                chmod 666 ${logOld}
                            fi

                            rm ${nl_nameOld}
                        fi
                    fi

            #new log
                if [[ ${option} == '-d' ]]; then
                    touch ${debugLog}
                    chmod 666 ${debugLog}
                    echo '' >> ${debugLog}
                    echo "Serverlog Omoti-debug $(hostname) (v${version})" >> ${debugLog}
                    echo $(date +'%Y-%m-%d') >> ${debugLog}
                    echo '--------------------------------------------------------------------------------------------------' >> ${debugLog}
                    echo 'Log-Code  Date        Time      User        Caller                Text' >> ${debugLog}
                    echo '--------------------------------------------------------------------------------------------------' >> ${debugLog}
                    echo '' >> ${debugLog}

                    #Write the log entry
                    logCode=$(printf '%-8s\n' 'DEBUG')
                    logCaller=$(printf '%-20s\n' 'NewLog')
                    user=$(printf '%-10s\n' 'System')
                    echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  New log file created" >> ${debugLog}

                else
                    touch ${logFile}
                    chmod 666 ${logFile}
                    echo '' >> ${logFile}
                    echo "Serverlog Omoti $(hostname) (v${version})" >> ${logFile}
                    echo $(date +'%Y-%m-%d') >> ${logFile}
                    echo '--------------------------------------------------------------------------------------------------' >> ${logFile}
                    echo 'Log-Code  Date        Time      User        Caller                Text' >> ${logFile}
                    echo '--------------------------------------------------------------------------------------------------' >> ${logFile}
                    echo '' >> ${logFile}

                    #Write the log entry
                    logCode=$(printf '%-8s\n' 'INFO')
                    logCaller=$(printf '%-20s\n' 'NewLog')
                    user=$(printf '%-10s\n' 'System')
                    echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  New log file created" >> ${logFile}
                fi
    }

    SetMonitoringStatus () {
        #Parameters
        #Dependencies
            #caller Script
                if [[ -z ${logCaller} ]] || [[ -z ${logCode} ]] || [[ -z ${logText} ]] || [[ -z ${monFile} ]] || [[ -z ${user} ]]; then
                    echo -e "\033[31m Error caller script data \033[0m"
                    exit 0
                fi

        #Variables
            #logCaller      -> Dependencies/caller Script
            #logCode        -> Dependencies/caller Script
            #logText        -> Dependencies/caller Script
            #monFile        -> Dependencies/caller Script
            sms_Version='0.1.1'
            #user           -> Dependencies/caller Script

        #Main
            #file
                if ! [[ -f ${monFile} ]]; then
                    touch ${monFile}
                    chmod 666 ${monFile}
                fi

            #entry
                echo 'New entry' >> ${monFile}
                (echo "${logCode}" | sed 's/ //g') >> ${monFile}
                (echo "${user}" | sed 's/ //g') >> ${monFile}
                (echo "${logCaller}" | sed 's/ //g') >> ${monFile}
                echo "${logText}" >> ${monFile}
    }

#Dependencies
    #parameters
        #       o_log
        if [[ -z ${para_1} ]]; then
            echo -e "\033[33mo_log: missing operand\033[0m"
            echo -e "Try '\033[36mo_log --help\033[0m' or '\033[36mo_log -?\033[0m' for more information"
            exit 0

        #       o_log -c $TEXT          o_log -d $TEXT              o_log -e $TEXT          o_log -i $TEXT          o_log -w $TEXT
        elif ([[ ${para_1} == '-c' ]]|| [[ ${para_1} == '-d' ]] ||[[ ${para_1} == '-e' ]] || [[ ${para_1} == '-i' ]] || [[ ${para_1} == '-w' ]]) && [[ ${para_2} ]] && [[ ${para_2} != '-s' ]] && [[ -z ${para_3} ]]; then
            option="${para_1}"
            logText="${para_2}"

        #       o_log -c -s                                         o_log -cs               o_log -sc                   o_log -s -c
        elif ([[ ${para_1} == '-c' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-s' ]]) || [[ ${para_1} == '-cs' ]] || [[ ${para_1} == '-sc' ]] || ([[ ${para_1} == '-s' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-c' ]]); then
            option='-c'
            showLog='true'

        #       o_log -d $CALLER $TEXT
        elif [[ ${para_1} == '-d' ]] && [[ ${para_2} ]] && [[ ${para_3} ]]; then
            option="${para_1}"
            logCaller="${para_2}"
            logText="${para_3}"

        #       o_log -d -s                                         o_log -ds               o_log -sd                   o_log -s -d
        elif ([[ ${para_1} == '-d' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-s' ]]) || [[ ${para_1} == '-ds' ]] || [[ ${para_1} == '-sd' ]] || ([[ ${para_1} == '-s' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-d' ]]); then
            option='-d'
            showLog='true'

        #       o_log -e -s                                         o_log -es               o_log -se                   o_log -s -e
        elif ([[ ${para_1} == '-e' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-s' ]]) || [[ ${para_1} == '-es' ]] || [[ ${para_1} == '-se' ]] || ([[ ${para_1} == '-s' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-e' ]]); then
            option='-e'
            showLog='true'

        #       o_log -i -s                                         o_log -is               o_log -si                   o_log -s -i
        elif ([[ ${para_1} == '-i' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-s' ]]) || [[ ${para_1} == '-is' ]] || [[ ${para_1} == '-si' ]] || ([[ ${para_1} == '-s' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-i' ]]); then
            option='-i'
            showLog='true'

        #       o_log -s
        elif [[ ${para_1} == '-s' ]] && [[ -z ${para_2} ]]; then
            option="${para_1}"
            showLog='true'

        #       o_log -w -s                                         o_log -ws               o_log -sw                   o_log -s -w
        elif ([[ ${para_1} == '-w' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-s' ]]) || [[ ${para_1} == '-ws' ]] || [[ ${para_1} == '-sw' ]] || ([[ ${para_1} == '-s' ]] && [[ ${para_2} ]] && [[ ${para_2} == '-w' ]]); then
            option='-w'
            showLog='true'

        #o_log -? / o_log --help
        elif [[ ${para_1} == '-?' ]] || [[ ${para_1} == '--help' ]]; then
            echo 'Usage: o_log OPTION... [TEXT]...'
            echo "o_log (v${version}) Manages the omoti log"
            echo ''
            echo 'Options:'
            echo '-c            creates an critical log entry with the text or displays all such entries in combination with -s'
            echo '-d            creates an debug log entry with the text or displays all such entries in combination with -s'
            echo '-e            creates an error log entry with the text or displays all such entries in combination with -s'
            echo '-i            creates an info log entry with the text or displays all such entries in combination with -s'
            echo '-s            show the log (no debug entries are displayed) or use -c, -d, -i, -w to filter'
            echo '-w            creates an warning log entry with the text or displays all such entries in combination with -s'
            echo '-? / --help   display this help and exit'
            echo ''
            echo 'Full documentation can be found in the Omoti Wiki'
            exit 0

        #compatibility with v1.x.x
        elif ([[ ${para_1} == 'I' ]] || [[ ${para_1} == 'W' ]] || [[ ${para_1} == 'E' ]] || [[ ${para_1} == 'C' ]]) && [[ ${para_2} ]] && [[ ${para_3} ]]; then
            if [[ ${para_1} == 'I' ]]; then
                option='-i'
            elif [[ ${para_1} == 'W' ]]; then
                option='-w'
            elif [[ ${para_1} == 'E' ]]; then
                option='-e'
            elif [[ ${para_1} == 'C' ]]; then
                option='-c'
            fi

            logText="OLD SYNTAX: ${para_2} | ${para_3}"

        else
            echo -e "\033[33mo_log: unrecognized option '${para_1}|${para_2}|${para_3}'\033[0m"
            echo -e "Try '\033[36mo_log --help\033[0m' or '\033[36mo_log -?\033[0m' for more information"
            exit 0
        fi

    #folder
        if ! [[ -d /srv/omoti/log/ ]]; then
            mkdir -p /srv/omoti/log/
            chmod 777 /srv/omoti/log/
        fi

    #variables
        #logCaller
            if [[ -z ${logCaller} ]]; then
                logCaller="$(basename "$(ps -o args= $PPID | awk '{print $2}')")"

                if [[ -z ${logCaller} ]]; then
                    logCaller='User-input'
                fi
            fi
            logCaller=$(printf '%-20s\n' ${logCaller})

        #logCode
            if [[ ${option} == '-c' ]]; then
                logCode='CRITICAL'
            elif [[ ${option} == '-d' ]]; then
                logCode='DEBUG'
            elif [[ ${option} == '-e' ]]; then
                logCode='ERROR'
            elif [[ ${option} == '-i' ]]; then
                logCode='INFO'
            elif [[ ${option} == '-w' ]]; then
                logCode='WARNING'
            fi
            logCode=$(printf '%-8s\n' ${logCode})

        #showLog
            showLog=${showLog:='false'}

        #user
            user=${USER}
            user=${user:='System'}
            user=$(printf '%-10s\n' ${user})

#Variables
    #dbEntry        -> Main/database/controll
    #dbToken        -> Main/database/token
    #dbUser         -> Main/database/user
    debugLog='/srv/omoti/log/debug.log'
    debugOld='/srv/omoti/log/old_debug.tar'
    #logCaller      -> Dependencies/parameters
    #logCode        -> Dependencies/variables/logCode
    #logDate        -> Main/new day
    logFile='/srv/omoti/log/server.log'
    logOld='/srv/omoti/log/old_log.tar'
    #logText        -> Dependencies/parameters
    monFile='/srv/omoti/log/.mon.status'
    #option         -> Dependencies/parameters
    #showLog        -> Dependencies/parameters
    #user           -> Dependencies/variables/user
    #para_1         -> Parameters
    #para_2         -> Parameters
    #para_3         -> Parameters
    #tmp            -> Temporary file
    #version        -> Version

#Main
    #show
        if [[ ${showLog} == 'true' ]]; then
            #no file
            if ! [[ -f ${logFile} ]] && [[ ${option} != '-d' ]]; then
                echo -e "\033[33mNo log file available\033[0m"
                exit 0
            fi

            #critical
            if [[ ${option} == '-c' ]]; then
                cp ${logFile} ${tmp}
                sed -i '/ERROR/d' ${tmp}
                sed -i '/INFO/d' ${tmp}
                sed -i '/WARNING/d' ${tmp}
                cat ${tmp}
                rm ${tmp}

            #debug
            elif [[ ${option} == '-d' ]]; then
                if [[ -f ${debugLog} ]]; then
                    cat ${debugLog}
                else
                    echo -e "\033[33mNo log file available\033[0m"
                fi

            #error
            elif [[ ${option} == '-e' ]]; then
                cp ${logFile} ${tmp}
                sed -i '/CRITICAL/d' ${tmp}
                sed -i '/INFO/d' ${tmp}
                sed -i '/WARNING/d' ${tmp}
                cat ${tmp}
                rm ${tmp}

            #info
            elif [[ ${option} == '-i' ]]; then
                cp ${logFile} ${tmp}
                sed -i '/CRITICAL/d' ${tmp}
                sed -i '/ERROR/d' ${tmp}
                sed -i '/WARNING/d' ${tmp}
                cat ${tmp}
                rm ${tmp}

            #all
            elif [[ ${option} == '-s' ]]; then
                cat ${logFile}

            #warning
            elif [[ ${option} == '-w' ]]; then
                cp ${logFile} ${tmp}
                sed -i '/CRITICAL/d' ${tmp}
                sed -i '/ERROR/d' ${tmp}
                sed -i '/INFO/d' ${tmp}
                cat ${tmp}
                rm ${tmp}
            fi

            exit 0
        fi

    #new log
        if [[ ${option} == '-d' ]]; then
            if ! [[ -f ${debugLog} ]]; then
                NewLog

            else
                logDate=$(sed -n '3p' ${debugLog} | tr -d '\r\n')

                if [[ ${logDate} != $(date +'%Y-%m-%d') ]]; then
                    NewLog
                fi
            fi
        else
            if ! [[ -f ${logFile} ]]; then
                NewLog
            else
                logDate=$(sed -n '3p' ${logFile} | tr -d '\r\n')

                if [[ ${logDate} != $(date +'%Y-%m-%d') ]]; then
                    NewLog
                fi
            fi
        fi

    #database
        #if [[ -f /srv/omoti/keys/access/mysql.cfg ]]; then
            #dbEntry='true'

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

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

    #log entry
        if [[ ${option} == '-c' ]]; then
            echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  ${logText}" >> ${logFile}
            SetMonitoringStatus

            if [[ ${dbEntry} ]]; then
                o_database ${dbUser} ${dbToken} "INSERT INTO server_manager (Code, Server, User, Caller, Text) VALUE (\"c\", \"$(hostname -s)\", \"${user}\", \"${logCaller}\", \"${logText}\");" 'n' 'logs'
            fi

        elif [[ ${option} == '-d' ]]; then
            echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  ${logText}" >> ${debugLog}

            if [[ ${dbEntry} ]]; then
                o_database ${dbUser} ${dbToken} "INSERT INTO server_manager (Code, Server, User, Caller, Text) VALUE (\"d\", \"$(hostname -s)\", \"${user}\", \"${logCaller}\", \"${logText}\");" 'n' 'logs'
            fi

        elif [[ ${option} == '-e' ]]; then
            echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  ${logText}" >> ${logFile}
            SetMonitoringStatus

            if [[ ${dbEntry} ]]; then
                o_database ${dbUser} ${dbToken} "INSERT INTO server_manager (Code, Server, User, Caller, Text) VALUE (\"e\", \"$(hostname -s)\", \"${user}\", \"${logCaller}\", \"${logText}\");" 'n' 'logs'
            fi

        elif [[ ${option} == '-i' ]]; then
            echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  ${logText}" >> ${logFile}

            if [[ ${dbEntry} ]]; then
                o_database ${dbUser} ${dbToken} "INSERT INTO server_manager (Code, Server, User, Caller, Text) VALUE (\"i\", \"$(hostname -s)\", \"${user}\", \"${logCaller}\", \"${logText}\");" 'n' 'logs'
            fi

        elif [[ ${option} == '-w' ]]; then
            echo "${logCode}  $(date +'%Y-%m-%d  %H:%M:%S')  ${user}  ${logCaller}  ${logText}" >> ${logFile}
            SetMonitoringStatus

            if [[ ${dbEntry} ]]; then
                o_database ${dbUser} ${dbToken} "INSERT INTO server_manager (Code, Server, User, Caller, Text) VALUE (\"w\", \"$(hostname -s)\", \"${user}\", \"${logCaller}\", \"${logText}\");" 'n' 'logs'
            fi
        fi