#!/bin/bash
#
#Server-Manager: o_newUser (System Command: Creates a new customer or client) [Power: 700]
#
#Version: 1.0.5
#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_newUser.$(date +'%H%M%S')$(pwgen -s -0 -N 1 2).tmp"

#Parameters
    option=${1}         #Option
    value=${2}          #Value

#Functions
    GetUser () {
        #Parameters
            gu_sample=${1}       #Name sample

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

            #caller script
                if [[ -z ${dbName} ]] || [[ -z ${dbToken} ]] || [[ -z ${dbUser} ]] || [[ -z ${result} ]]; then
                    echo -e "\033[31mError caller script data\033[0m"
                    exit 0
                fi

        #Variables
            #dbName         -> Dependencies/caller script
            #dbToken        -> Dependencies/caller script
            #dbUser         -> Dependencies/caller script
            #result         -> Dependencies/caller script
            gu_i='0'
            #gu_name        -> Main/get name
            #gu_sample      -> Parameters
            gu_tmp='false'
            gu_version='1.0.1'

        #Main
            #get data
                o_database ${dbUser} ${dbToken} "SELECT User FROM ClientServer WHERE User LIKE \"${gu_sample}%\";" 'n' ${dbName}

                if [[ -z $(sed -n '2p' ${result}) ]]; then
                    o_log -d "No user found with the prefix ${gu_sample}"
                fi

            #get name
                while [[ ${gu_tmp} ]]; do
                    ((gu_i++))
                    gu_name="${gu_sample}$(printf '%02d' "${gu_i}")"
                    gu_tmp=$(cat ${result} | grep "${gu_name}")
                done

            #controll
                o_database ${dbUser} ${dbToken} "SELECT User FROM ClientServer WHERE User = \"${gu_name}\"" 'n' ${dbName}

                if [[ $(sed -n '2p' ${result}) ]]; then
                    echo "Could not find a free username"
                    o_log -c 'Could not find a free username'
                    gu_name="${gu_sample}00"
                fi

            unset gu_i gu_sample gu_tmp
    }

#Dependencies
    #parameters
        if [[ -z ${option} ]] || ([[ ${option} != '-n' ]] && [[ ${option} != '-k' ]]) || [[ -z ${value} ]]; then
            echo
            echo -e "\033[31m!!! Wrong parameters !!!\033[0m"
            echo
            echo 'New client:'
            echo -e "o_newUser \033[36m -n <Client name>\033[0m"
            echo
            echo 'New customer:'
            echo -e "o_newUser \033[36m -k <Customer number>\033[0m"
            echo
            exit 0
        fi

    #client
        if [[ ${option} == '-n' ]]; then
            if getent passwd ${value} > /dev/null; then
                echo -e "\033[31mUser (${value}) already exists\033[0m"
                exit 0
            fi
        fi

    #customer
        if [[ ${option} == '-k' ]]; then
            #mysql keys
                if ! [[ -d /srv/omoti/keys/mysql/ ]]; then
                    echo -e "\033[31mMySQL ssl certificates are required\033[0m"
                    exit 0
                fi

            #access
                if ! [[ -f /srv/omoti/keys/access/mysql.cfg ]]; then
                    access='false'
                    echo
                    echo
                    echo 'Database customer server access'
                    echo
                    read -p 'User: ' dbUser
                    read -sp 'Password: ' dbToken
                    echo

                    if [[ -z ${dbUser} ]] && [[ -z ${dbToken} ]]; then
                        echo -e "\033[31mError during data entry! (Database customer server access)\033[0m"
                        echo 'Please start again'
                        exit 0
                    fi
                else
                    access='true'
                fi
        fi

#Variables
    #access         -> Dependencies/customer
    dbName='server_manager'
    #dbToken        -> Dependencies/customer/access | Main/customer/access/token
    #dbUser         -> Dependencies/customer/access | Main/customer/access/user
    #gu_name        -> Functions/GetName
    #newUser        -> Main/customer/get username
    #option         -> Parameters
    result='/srv/omoti/.db_result.tmp'
    #tmp            -> Temporary file
    #value          -> Parameters
    #version        -> Version

#Main
    #scripts
        #backup.sh
            if ! [[ -f /srv/omoti/scripts/backup.sh ]]; then
                cd /srv/omoti/scripts/
                o_download -a 'https://mgmt.omoti.de/User/Basics/backup.sh'
                chmod 700 backup.sh
                cd

                #crontab
                    echo '30 5 * * * root /srv/omoti/scripts/backup.sh' >> /etc/crontab
            fi

        #termination.sh
            if ! [[ -f /srv/omoti/scripts/termination.sh ]]; then
                cd /srv/omoti/scripts/
                o_download -a 'https://mgmt.omoti.de/User/Basics/termination.sh'
                chmod 700 termination.sh
                cd
            fi

        #statusCheck.sh
            if ! [[ -f /srv/omoti/scripts/statusCheck.sh ]]; then
                cd /srv/omoti/scripts/
                o_download -a 'https://mgmt.omoti.de/User/Basics/statusCheck.sh'
                chmod 700 statusCheck.sh
                cd

                #crontab
                    echo '20 * * * * root /srv/omoti/scripts/statusCheck.sh' >> /etc/crontab
            fi

        #updateCustomer.sh
            if ! [[ -f /srv/omoti/scripts/updateUser.sh ]]; then
                cd /srv/omoti/scripts/
                o_download -a 'https://mgmt.omoti.de/User/Basics/updateUser.sh'
                chmod 700 updateUser.sh
                cd
            fi

    #client
        if [[ ${option} == '-n' ]]; then
            newUser=${value}
        fi

    #customer
        if [[ ${option} == '-k' ]]; then
            #access
                if [[ ${access} == 'false' ]]; then
                    cd /srv/omoti/keys/access/
                    o_download -a 'https://mgmt.omoti.de/Parts/Manager/access.cfg'
                    mv access.cfg mysql.cfg
                    cd

                    sed -i "s/-user=false/-user=${dbUser}/g" /srv/omoti/keys/access/mysql.cfg
                    sed -i "s/-token=false/-token=${dbToken}/g" /srv/omoti/keys/access/mysql.cfg
                elif [[ ${access} == 'true' ]]; then
                    #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#*=}

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

            #get username
                value=$(printf '%02d' "${value}")
                GetUser "k${value}gs"
                newUser="${gu_name}"

                if [[ ${newUser} ]]; then
                    o_log -d "New username ${newUser}"
                else
                    newUser="k${value}gs00"
                    o_log -e "Error with the variable transfer"
                fi
        fi

    #add user
        if getent passwd ${newUser} > /dev/null; then
            if [[ -f ${result} ]]; then
                rm ${result}
            fi

            echo -e "\033[31mUser (${newUser}) already exists\033[0m"
            exit 0
        else
            useradd -b /opt/ -c '' -g omoti -m -N -s /bin/bash ${newUser}
        fi
        if [[ ${option} == '-k' ]]; then
            o_database ${dbUser} ${dbToken} "INSERT INTO ClientServer (User, Server) VALUE (\"${newUser}\", \"$(hostname -s)\");" 'n' ${dbName}
        fi

    #login info
        #client
            if [[ ${option} == '-n' ]]; then
                echo 'echo -e "\033[33m You have changed to a client\033[0m"' >> /opt/${newUser}/.profile
                echo 'echo' >> /opt/${newUser}/.profile
            fi

        #customer
            if [[ ${option} == '-k' ]]; then
                echo 'echo -e "\033[33m You have changed to a customer\033[0m"' >> /opt/${newUser}/.profile
                echo 'echo' >> /opt/${newUser}/.profile
            fi

    #default files
        o_download -a 'https://mgmt.omoti.de/User/Server/start.sh'
        o_download -a 'https://mgmt.omoti.de/User/Server/stop.sh'
        o_download -a 'https://mgmt.omoti.de/User/Server/restart.sh'
        o_download -a 'https://mgmt.omoti.de/User/Server/server.cfg'

        mv start.sh /opt/${newUser}/
        mv stop.sh /opt/${newUser}/
        mv restart.sh /opt/${newUser}/
        mv server.cfg /opt/${newUser}/

        mkdir /opt/${newUser}/Server/

        chmod 705 /opt/${newUser}/start.sh /opt/${newUser}/stop.sh /opt/${newUser}/restart.sh
        chmod 770 /opt/${newUser}/Server/
        chmod 660 /opt/${newUser}/server.cfg

        chown ${newUser}:omoti /opt/${newUser}/Server/
        chown :omoti /opt/${newUser}/server.cfg

    if [[ ${option} == '-n' ]]; then
        echo "Client ${newUser} was createt"
        echo
        o_log -i "Client ${newUser} was createt"
    
    elif [[ ${option} == '-k' ]]; then
        echo "Customer ${newUser} was createt"
        echo
        o_log -i "Customer ${newUser} was createt"
    fi

    if [[ -f ${result} ]]; then
        rm ${result}
    fi
