#!/bin/bash
#
#Server-Manager: o_database (System Command: Communicates with the omoti main database) [Power: 755]
#
#Version: 0.0.18
#Date:    2024.05.17
#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_database.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).tmp"

#Parameters
    user=${1}           #Database user
    userPW=${2}         #Database user password
    command=${3}        #Database command
    logEntry=${4}       #Log entry (y/n)
    name=${5}           #Database name (name)

#Functions
#Dependencies
    #log entry & name
        if [[ -z ${logEntry} ]] && [[ -z ${name} ]]; then
            logEntry='y'
            name='false'
        elif [[ ${logEntry} ]] && [[ -z ${name} ]]; then
            if [[ ${logEntry} != 'y' ]] && [[ ${logEntry} != 'n' ]]; then
                name=${logEntry}
                logEntry='y'
            else
                name='false'
            fi
        fi

    #controll
        if [[ -z ${user} ]] || [[ -z ${userPW} ]] || [[ -z ${command} ]] || [[ -z ${logEntry} ]] || [[ -z ${name} ]]; then
            echo
            echo -e "\033[31m!!! Wrong parameters !!! \033[0m"
            echo -e "o_database \033[36m <DB user> <DB password> <DB command> <optional: DB name>\033[0m"
            echo
            exit 0
        fi

#Variables
    host='mysql.omoti.org'
    port='8320'
    result='/srv/omoti/.db_result.tmp'

#Main
    #delete old result
        if [[ -f ${result} ]]; then
            rm -f ${result}
        fi

    #execute command
        if [[ ${name} == 'false' ]]; then
            mysql --host=${host} -P ${port} --user=${user} --password=${userPW} --execute="${command}" > ${result}
        else
            mysql --host=${host} -P ${port} --user=${user} --password=${userPW} --database=${name} --execute="${command}" > ${result}
        fi

    #log
        if [[ ${logEntry} == 'y' ]]; then
            o_log -i "Access to the database ${name}"
        fi