#!/bin/bash
# Program:
#   Check DRBL client status
# Author: 
#   Jazz, Rock {jazz, rock}@nchc.org.tw
# Version:
#    1.0
# History:                                                                                          
#   2010/08/29  Rock    First release (1.0) 

source /opt/drbl-virt/conf/drbl-virt.conf
source $Work_Path/functions_drbl_virt


# [Varliables]
client_IPs=$(cat $Work_Home/etc/IP_HOST_TABLE | grep -v "#" | awk '{print $1}')
drbl_client_file="/tmp/drbl_client_status.$$"
drbl_client_top_file="/tmp/drbl_client_top.$$"


# [Main] 
drbl_sshkey
for client_IP in $client_IPs
do
    # local variables
    client_hostname="$(cat $Work_Home/etc/IP_HOST_TABLE | grep -v "#" | grep $client_IP | awk '{print $2}')"
    IP_status="online"
    client_CPU_core=""
    client_Ram=""
    client_idle_CPU=""
    client_unused_Ram=""
    # check network status
    ping -c1 -w1 $client_IP > /dev/null 2>&1 || IP_status="offline"

    if [ $IP_status == "online" ]; then
        # check CPU core
        client_CPU_core=$(ssh -o StrictHostKeyChecking=no $client_IP "cat /proc/cpuinfo |grep processor | wc -l")
        # check top information
        ssh -o StrictHostKeyChecking=no $client_IP "top -b -n2 -d1 | awk '/^top/{i++}i==2'" > $drbl_client_top_file
IP_VM_right_line=""
        client_idle_CPU=$(cat $drbl_client_top_file | grep ^Cpu | sed 's/^.*ni,//' | sed 's/id,.*$//'  | awk '{print $1}')
        client_Ram=$(cat $drbl_client_top_file | grep ^Mem | sed 's/total.*$//' | sed 's/^Mem://' | awk '{print $1}')
        client_unused_Ram=$(cat $drbl_client_top_file | grep ^Mem | sed 's/^.*used,//' | sed 's/free.*$//' | awk '{print $1}')
    
    fi

echo "[$client_hostname $client_IP] $IP_status CPU_Core=$client_CPU_core Ram=$client_Ram idle_CPU=$client_idle_CPU unused_Ram=$client_unused_Ram"
#echo "[$client_hostname $client_IP] $IP_status $client_CPU_core $client_Ram $client_idle_CPU $client_unused_Ram" >> $drbl_client_file

done

# delete tmp file
rm -f $drbl_client_top_file
