#!/bin/bash
#
#Server-Manager: o_statusCheck (System Command: Displays the current status of a client server) [Power: 755]
#
#Version: 0.1.4
#Date:    2022.03.09
#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_statusCheck.tmp'

#Parameters
    user=${1}

#Functions
#Dependencies
    #user
        if [ -z "${user}" ]; then
            user=${USER}
            ex='false'
        else
            ex='true'
        fi

    #server.cfg
        if [ -f /home/${user}/server.cfg ]; then
            dir='home'
        elif [ -f /opt/${user}/server.cfg ]; then
            dir='opt'
        else
            echo -e "\033[31m Error \033[0m"
            echo -e "\033[33m No server config available \033[0m"
            echo " Please contact an administrator!"
            o_log -e 'No server config available'
            exit 0
        fi

    #variant
        variant=$(sed -n '/-variant/=' /${dir}/${user}/server.cfg)
        variant=$(sed -n "${variant}p;$((variant++))q" /${dir}/${user}/server.cfg)
        variant=${variant#*=}

#Variables
    #dir    -> Dependencies/server.cfg
    #ex     -> Dependencies/user

#Main
    if [ ${variant} == 'game' ]; then
        if [ ${ex} == 'true' ]; then
            su ${user} -c "screen -ls > ${tmp}"
        else
            screen -ls > ${tmp}
        fi
        if grep -q 'No Sockets found' ${tmp}; then
            echo 'offline'
        elif grep -q 'There is a screen on' ${tmp}; then
            echo 'online'
        elif grep -q 'There are screens on' ${tmp}; then
            echo 'multiple'
        else
            echo 'error01'
        fi
    elif [ ${variant} == 'voice' ]; then
        /${dir}/${user}/Server/ts3server_startscript.sh status &> ${tmp}
        if grep -q 'No server running' ${tmp}; then
            echo 'offline'
        elif grep -q 'Server seems to have died' ${tmp}; then
            echo 'offline'
        elif grep -q 'Server is running' ${tmp}; then
            echo 'online'
        else
            echo 'error02'
        fi
    else
        echo 'error00'
    fi
    rm ${tmp}