#! /bin/bash

log_file=check_`date +%F_%T`.log
temp_file=`mktemp memory.XXX`


echo `hostname -i` >> $log_file
echo "login system successful" >> $log_file


divider() {
    if [ "$1" ]
    then
        echo "################# $1 #################"
    else
        echo " ###########################################################"
    fi
}


uptime_check() {
    divider "uptime check" >> $log_file
    uptime | awk -F, '{ print $1","$2 }' >> $log_file
}

get_top() {
    top -b -n 1 >> $temp_file
}

cpu_check() {
    divider "cpu check" >> $log_file
    top -b -n 1 > $temp_file
    head -n 1 $temp_file | awk -F" {2}" '{ print $NF }' >> $log_file
}
disk_check() {
    divider "disk check" >> $log_file
    df -h | grep -v docker | grep -v kubelet >> $log_file
}

memory_check() {
    divider "memory check" >> $log_file
    free -h >> $log_file
    echo "top 10 memory used process:" >> $log_file
    top -b -n 1 > $temp_file
    tail -n +8 $temp_file | awk '{array[$NF]+=$6}END{for (i in array) print array[i],i}' |sort -k 1 -n -r|head -10 >> $log_file
}

security_check() {
    divider "security check: login use" >> $log_file
    w >> $log_file
    divider "security check: login history" >> $log_file
    last > $temp_file
    head -10 $temp_file >> $log_file
}

socket_check() {
    divider "socket check" >> $log_file
    ss -tunlp >> $log_file
}

cron_check() {
    divider "crontab check" >> $log_file
    crontab -l >> $log_file
}



uptime_check
cpu_check
memory_check
disk_check
security_check
socket_check
cron_check
rm -f $temp_file
