#!/bin/bash

filename=$(basename $0)
cnt=`pgrep -c $filename`

if [ $cnt -gt 1 ]; then
    echo "Already Running..."
    exit 0
fi


echo "Running Start..."

SSIP_API_URI="http://192.168.202.106:8444/api/system-status2"
SSIP_API_TIMEOUT=3
HEADER_CONTEXT_TYPE="Content-Type: application/json"

HostName=$(hostname)
UpTime=""
MemoryUsage=0
DiskUsage=0
CpuLoad=0

function check_health {
    #Memory 사용율
    MemoryUsage=$(free -m | awk 'NR==2{printf "%.2f", $3*100/$2 }')
    
    #DISK 사용율
    totaldisk=$(df -P | grep -v ^Filesystem | awk '{sum += $2} END { print sum; }')
    useddisk=$(df -P | grep -v ^Filesystem | awk '{sum += $3} END { print sum; }')
    DiskUsage=$((100*$useddisk/$totaldisk))

    #CPU 부하
    CpuLoad=$(top -bn1 | grep load | awk '{printf "%.2f", $(NF-2)}')
}

function call_system_status_api {
    # Call System Status Save REST API
    PAYLOAD='{"hostName"    : "'${HostName}'",
              "memoryUsage" : '${MemoryUsage}',
              "diskUsage"   : '${DiskUsage}',
              "cpuLoad"     : '${CpuLoad}'
            }'

    echo -e "api call:"
    api_result=$(curl -d "${PAYLOAD}" -X POST $SSIP_API_URI -H "$HEADER_CONTEXT_TYPE" --connect-timeout $SSIP_API_TIMEOUT)

    # Result
    echo -e ""
    echo -e "api call result: ${api_result} "
}

function print_health {
    echo -e "
    Hostname       : $HostName 
    Memory Usage   : $MemoryUsage
    Disk   Usage   : $DiskUsage
    CPU    Load    : $CpuLoad "
}

while :; do
    check_health;
    call_system_status_api;
    print_health;
    sleep 10
done
