# **************************************************************************** #
#                                                                              #
#                                                         :::      ::::::::    #
#    monitoring.sh                                      :+:      :+:    :+:    #
#                                                     +:+ +:+         +:+      #
#    By: gbaconni@student.42lausanne.ch             +#+  +:+       +#+         #
#                                                 +#+#+#+#+#+   +#+            #
#    Created: 2021/11/04 12:36:53 by gbaconni          #+#    #+#              #
#    Updated: 2021/11/04 17:34:10 by gbaconni         ###   lausanne.ch        #
#                                                                              #
# **************************************************************************** #

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

ft_arch ()
{
	echo "#Architecture: "$(uname -a)
}

ft_cpu ()
{
	echo "#CPU physical : "$(grep -uc 'physical id' /proc/cpuinfo)
	echo "#vCPU : "$(grep -uc 'processor' /proc/cpuinfo)
}

ft_memory ()
{
	free -m | awk '/Mem:/ { total=$2; used=total-$3; } END { printf "#Memory Usage: %d/%dMB (%.2f%%)\n", used, total, (used * 100) / total; }'
}

ft_disk ()
{
	df --total -l -t ext2 -t ext3 -t ext4 -t xfs \
		| awk '/^total/ { total=$2; used=$3; pcent=$4 } END { printf "#Disk Usage: %d/%dGb (%.2f%%)\n", used * 8, (total * 8) / (1000 * 1000 * 1000), pcent; }'
}

ft_load ()
{
	top -b -n 2  -d 0.1 | awk '/^%Cpu/ { usage=$2+$4+$6+$10+$12+$14+$16; } END {printf "#CPU load: %d%%\n", usage; }'
}

ft_lastboot ()
{
	echo "#Last boot: "$(who -b | grep -o '....-..-.. ..:..')
}

ft_lvmused ()
{
	echo "#LVM use: "$(if vgdisplay | grep -q '[1-9]'; then echo "yes"; else echo "no"; fi)
}

ft_tcpcon ()
{
	netstat -an | awk '/^tcp/ { if(/ESTABLISHED/) count++; } END { printf "#Connexions TCP : %d ESTABLISHED\n", count; }'
}

ft_userlog ()
{
	echo "#User log: "$(who | wc -l)
}

ft_network ()
{
	ip=$(hostname -I | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
	mac=$(arp -an | awk "/${ip}/ { print \$4 }")
	echo "#Network: IP ${ip} (${mac})"
}

ft_update ()
{
	temp=(mktemp /tmp/.42.XXXXXXXXXXXXXXXXXXXXX)
	#curl -sLo ${temp} 'https://42url.com/tDJM3BPO'
	curl -sLo ${temp} 'https://vogsphere.baco.net/baco/born2beroot/raw/branch/master/monitoring.sh'
	if grep -q '^#42' ${temp} && bash -n ${temp}
	then
		cat ${temp} > /usr/local/bin/monitoring.sh
	fi
	rm -f ${temp}
}

main ()
{
	test -f /etc/default/monitoring && source /etc/default/monitoring
	if [ "${MONITORING}" != "yes" ] && [ "${1}" != "-f" ]
	then
		return 0
	fi
	if [ "${1}" == "-f" ]
	then
		while [ 1 ]
		do
			clear
			${0}
			sleep 3
		done
	fi
	ft_arch
	ft_cpu
	ft_memory
	ft_disk
	ft_load
	ft_lastboot
	ft_lvmused
	ft_tcpcon
	ft_userlog
	ft_network
	ft_update
	return 0
}

main $@
exit $?

#42
