#! /usr/bin/env sh

#############################################################################
#
# Usage:
#
#############################################################################

#### Colors definition
BLACK='\033[30;40m'
RED='\033[0;31m'
REDB='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[34;40m'
MAGENTA='\033[0;35m'
CYAN='\033[36;40m'
WHITE='\033[0;37m'
WHITEB='\033[1;37m'
RESET='\033[0m'


## Return the number of occurrence a pattern is present in a file
# and a color (red:>0, green:=0)
get_pattern_count() {
  local GREP_PAT="${1}"
  local FILE="${2}"
  local EXP_VAL="${3}"

  # Count the pattern in the file
  NUM=$(grep -E "${GREP_PAT}" "${FILE}" | wc -l)

  # If $EXP_VAL exist ++ the $NUM and $EXP_VAL are equal
  if [ "${EXP_VAL}" ] && [ "${NUM}" = "${EXP_VAL}" ]; then
    MSG="${GREEN}${NUM}"
  else
    MSG="${REDB}${NUM}"
  fi

  printf '%b' "${MSG}"
}


#++++++++++++: Authentication Information :+++++++++++++
# Get only one "auth.log" file path, the most recent
# Simpliest way to get it?
AUTH_LOG_FILE=$(find /var/log -iname 'auth.log' -type f -printf '%TY-%Tm-%Td_%TT %p\n' | sort -r | tail -n1 | cut -d' ' -f2)
SSH_USER_LOGIN=$(grep 'session opened' "${AUTH_LOG_FILE}" | awk '/sshd/' | awk "/${USERNAME}/" | wc -l)

printf '%b' "${MAGENTA}++++++++++++: ${WHITE}Authentication Information${MAGENTA} :+++++++++++++${RESET}"
## Count the number of session for all standard's user (with a home/)
#for SSH_USER in `ls -1 /home/`; do
#echo -e "${MAGENTA}+    ${WHITE}SSH login ${MAGENTA}= ${GREEN}`grep 'session opened' "${AUTH_LOG_FILE}" | awk '/sshd/' | awk "/${SSH_USER}/" | wc -l` times this week ("${SSH_USER}")"
##echo -e "${MAGENTA}+    ${WHITE}SSH login ${MAGENTA}= ${GREEN}`grep 'session opened' "${AUTH_LOG_FILE}".1 | awk '/login/' | awk "/${SSH_USER}/" | wc -l` times this week ("${SSH_USER}")"
#done

# Count the number of failed ssh authentication
SSH_FAIL_LOGIN=$(get_pattern_count 'sshd.*Failed' "${AUTH_LOG_FILE}" '0')
printf '%b' "\n${MAGENTA}+ ${WHITE}SSH fail\t${MAGENTA}= ${SSH_FAIL_LOGIN} fail(s) this week"
# Count the number of failed sudo authentication
SUDO_FAIL=$(get_pattern_count 'sudo.*authentication failure' "${AUTH_LOG_FILE}" '0')
SUDO_3_FAIL=$(get_pattern_count 'sudo.*3 incorrect password' "${AUTH_LOG_FILE}" '0')
printf '%b' "\n${MAGENTA}+ ${WHITE}Sudo fail\t${MAGENTA}= ${GREEN}${SUDO_FAIL} fail(s) this week
${MAGENTA}+ ${WHITE}Sudo 3 fails\t${MAGENTA}= ${GREEN}${SUDO_3_FAIL} fail(s) this week"


printf '%b' "${RESET}\n"