#!/bin/bash

if [[ -z "${WELCOME_SCRIPT_PATH}" ]]; then
  WELCOME_SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." &>/dev/null && pwd)"
fi

#region INCLUDES
. "${WELCOME_SCRIPT_PATH}/config/config_colors.sh"
#endregion

check_ssh_failed_logins() {
    local failed_con
    local sudo_cmd=""

    # Détection sudo pour journalctl
    [[ $EUID -ne 0 ]] && command -v sudo >/dev/null && sudo_cmd="sudo"

    failed_con=$($sudo_cmd journalctl _SYSTEMD_UNIT=ssh.service --since "24 hours ago" 2>/dev/null | grep -c "Failed password")

    if [[ ${failed_con:-0} -gt 0 ]]; then
        echo -e " ${COLOR_LIGHT_RED}⚡ ATTENTION :${COLOR_GRAY} ${failed_con} tentatives de connexion échouées ces dernières 24h !${NONE}"
        echo -e "${COLOR_GREEN}======================================================================${NONE}"
    fi
}

check_active_sessions() {
    local other_users

    other_users=$(who | wc -l)

    if [[ ${other_users:-0} -gt 1 ]]; then
        echo -e " ${COLOR_LIGHT_RED}⚡ ATTENTION :${COLOR_GRAY} Il y a actuellement $((other_users - 1)) autre(s) session(s) active(s).${NONE}"
        echo -e "${COLOR_LIGHT_RED}   ╔════════════════════════════════════════════════╗"
        printf "   ║ %-10s %-10s %-8s %-15s ║\n" "USER" "DATE" "HEURE" "IP"
        echo "   ╠════════════════════════════════════════════════╣"

        # Le flux 'who' est traité par awk pour le formatage des colonnes
        who | awk '{
            u=$1;
            # Si le dernier champ contient des parenthèses, c est une IP
            if ($NF ~ /^\(.*\)$/) {
                ip=$NF; gsub(/[()]/,"",ip);
                t=$(NF-1); d=$(NF-2);
            } else {
                ip="console"; t=$NF; d=$(NF-1);
            }
            printf "   ║ %-10s %-10s %-8s %-15s ║\n", u, d, t, ip
        }'

        echo -e "   ╚════════════════════════════════════════════════╝${NONE}"
        echo -e "${COLOR_GREEN}======================================================================${NONE}"
    fi
}


check_ssh_failed_logins
check_active_sessions