template-bash/script.sh
2023-05-01 16:59:58 +03:00

126 lines
2.3 KiB
Bash

#!/usr/bin/env bash
# DESCRIPTION:
# returning current username if privileged rights are exist
# or
# returning error, if privileged rights are not exist
#
# DEPENDENCIES:
# - whoami
#
# PARAMETERS:
# 1: "qn" - execution without pauses
# 2: custom configuration file path
#
# FUNCTIONS:
#
#######################################
# Print message and add to log.
# Globals:
# logs
# Arguments:
# 1: message to print and logging
#######################################
addtologs() {
echo "$(date +'%Y.%m.%d-%H:%M:%S') $1" | tee -a "${logs}"
}
#######################################
# Waiting for press [ENTER].
# Globals:
# None
# Arguments:
# None
#######################################
execpause() {
read -r -p "Press [ENTER] to continue... "
}
#######################################
# Exit procedure.
# Globals:
# show
# Arguments:
# None
#######################################
execquite() {
addtologs "execution time is $(($(date +%s)-time)) seconds, exit"
if [ "${show}" != "qn" ]; then
execpause
fi
exit
}
#######################################
# Error exit procedure
# Globals:
# None
# Arguments:
# 1: message to print and logging
#######################################
execerror() {
addtologs "error: $1"
execquite
}
#######################################
# Parsing config file and creating global vars.
# Globals:
# None
# Arguments:
# None
#######################################
getconfig() {
logs=$(grep "logs=" "${conf}" | cut -d= -f2)
}
#######################################
# Checking user rights.
# Globals:
# None
# Arguments:
# None
# return:
# 0 - if privileged rights, 1 - if not privileged rights
#######################################
checkroot() {
if [ "${EUID}" -ne 0 ]; then
return 1 # false
else
return 0 # true
fi
}
#
# VARIABLES:
#
show=$1
conf=$2
if [ -z "${conf}" ] || [ "${conf}" == "-" ]; then
conf="$(dirname "$(realpath "$0")")/$(basename -s .sh "$0").conf"
fi
time=$(date +%s)
cd "$(dirname "$(realpath "$0")")" || execerror
if [ ! -e "${conf}" ]; then
:
else
getconfig
fi
if [ -z "${logs}" ]; then
logs=/dev/null
elif [ ! -e "${logs}" ]; then
touch "${logs}"
fi
#
# MAIN:
#
checkroot \
&& echo "Running as $(whoami)" \
&& execquite \
|| execerror "Restart this as root!"