#!/bin/bash function message() { red="\e[1;31m" yellow="\e[1;33m" blue="\e[36m" if [ -z "${APP}" ]; then app=$(basename "${0}" .sh) else app="${APP}" fi current_date=$(date '+%Y-%m-%d %H:%M:%S') text="${1}" if [ -n "${text}" ]; then if [ ${#} -gt 1 ]; then print="${2}" shift else print="" fi if [ ${#} -gt 1 ]; then extra_args="${2}" shift subject="${2}" shift recipient="${2}" shift else extra_args="" fi # shellcheck disable=SC2153 if [ -z "${LOG_FILE}" ];then if [ -w /var/log ]; then log_file="/var/log/${app}.log" else mkdir -p "${HOME}/log/" log_file="${HOME}/log/${app}.log" fi else log_file="${LOG_FILE}" fi mkdir -p "$(dirname "${log_file}")" if [[ "${print}" =~ [Ww][Aa][Rr][Nn] ]]; then echo -e "${yellow}${current_date} ${text}" else if [[ "${print}" =~ [Ee][Rr][Rr] ]]; then >&2 echo -e "${red}${current_date} ${text}" else if [[ ( -n "${DEBUG}" ) && ( "${DEBUG}" == "true" ) || ( "${DEBUG}" -gt "0" ) ]] || [[ "${print}" =~ [Pp] ]] || [[ "${print}" =~ [Pp][Rr][Ii][Nn][Tt] ]]; then echo -e "${blue}${current_date} ${text}" fi fi fi echo "${current_date} ${text}" >> "${log_file}" logger -t "${app}" "${text}" if [ "${extra_args}" == "to_mail" ]; then echo "${text}" | mail -s "${subject}" "${recipient}" fi fi } function run_and_log() { extra_args="" if [ "${1}" == "to_mail" ]; then extra_args="to_mail" shift subject="${1}" shift recipient="${1}" shift fi CMD=$* message "Running and logging: ${CMD}" if [[ ( -n "${DEBUG}" ) && ( "${DEBUG}" == "true" ) ]]; then temp_file=$(mktemp /tmp/tmp.XXXX.log) message "Debug log file '${temp_file}'" output=$(${CMD} 2>&1 |tee "${temp_file}") else output=$(${CMD} 2>&1) fi return_code="${?}" for line in "${output[@]}" do message "${line}" "${extra_args}" "${subject}" "${recipient}" done <<< "${output[@]}" if [ "${return_code}" != "0" ]; then message "Command run finished with error ${return_code}." "${extra_args}" "${subject}" "${recipient}" else message "Command ran without errors." "${extra_args}" "${subject}" "${recipient}" fi }