#!/bin/bash

function unit_convert() {
    typeset -l size
    size=$1
    to_gb=$(echo $size | awk '{
            if ($1 ~ /pb$/ || $1 ~ /p$/){
                print $1 * 1024 * 1024
            } else if ($1 ~ /tb$/ || $1 ~ /t$/){
                print $1 * 1024
            } else if ($1 ~ /gb$/ || $1 ~ /g$/){
                print $1
            } else if ($1 ~ /mb$/ || $1 ~ /m$/){
                print $1/1024
            } else if ($1 ~ /kb$/ || $1 ~ /k$/){
                print $1/1024/1024
            } else if ($1 ~ /b$/){
                print $1/1024/1024/1024
            }
        }')
    echo $to_gb
}

function main() {
    REQ_MEM=32G
    mem_total=$(cat /proc/meminfo | awk '/MemTotal:/{print $2$3}')
    mem_gb=$(unit_convert $mem_total)
    req_mem=${REQ_MEM:0:-1}

    if [[ -n ${req_mem} && -n ${mem_gb} ]]; then
        if [[ $(awk 'BEGIN{print('"$mem_gb"'<'"$req_mem"')?0:1}') -eq 0 && $(awk 'BEGIN{print('"$mem_gb"'-'"$req_mem"'<=-1)?0:1}') -eq 0 ]]; then
            checkStatus=fail
            msg="内存小于${REQ_MEM}"
        else
            checkStatus=OK
            msg="内存大于${REQ_MEM}"
        fi
    else
        checkStatus=fail
        msg="获取主机内存失败"
    fi

    echo "{\"checkValue\":\"${mem_gb}\", \"checkStatus\":\"${checkStatus}\", \"msg\":\"${msg}\"}"
}

main
