#!/bin/sh

TODY_ID_STR=`date +"%Y%m%d"`
# 日志文件存放
MONITOR_LOG="/home/data/log/ping_monitor_$TODY_ID_STR.log"
# SD写卡测试日志文件(会不停的添加日志, 会记录SD卡写入耗时, 如果置空则不进行测试)
SD_LOG=""
# 网络监测地址
host_ip=119.96.169.117
echo "log: $MONITOR_LOG"

# wget http://119.96.169.117:3000/kpl-release/release/kpl-check-ping.sh -O kpl-check-ping.sh&&sleep 1s&&chmod +x kpl-check-ping.sh

ping_monitor()
{
    ping -c 3 $1 > /dev/null
    ping_code=$?
    if [ $ping_code -eq 0 ];then
        echo "`date +"%Y/%m/%d %H:%M:%S"` $1 ping success" >>${MONITOR_LOG} 2>&1
    else
        echo "`date +"%Y/%m/%d %H:%M:%S"`[error] $1 ping failed" >>${MONITOR_LOG} 2>&1
    fi
}

ping_check() { 
  local total="0"
  local i="0"
  
   
  while [ $i -lt 10 ]; do
    local line=""
    # 1 packets transmitted, 1 packets received, 0% packet loss
    line=`ping $1 -c 1 -W 1 | grep " 0% packet loss" | wc -l`

    if [ "${line}" != "1" ]; then
      echo "ping failed!"
      total=$((total+1))
    else
      echo "ping ok!"
      total="0"
    fi
    i=$((i+1))
    sleep 1
  done

  if [ $total -gt 1 ]; then
    echo "check failed!"
    return 1
  else 
    echo "check ok!"
    return 0
  fi
}


i=0
lastT=$(date +%s)
sleep 1s
while [ 1 ]; do
  #ping_monitor www.baidu.com
  nowT=$(date +%s)
  sleepT=$(($nowT-$lastT))

  
  if [ $sleepT -gt 65 ]; then
    sleepT="$sleepT(sleep timout)"
  else
    sleepT="$sleepT(sleep)"
  fi
  
  cpuv=`top -n1 | fgrep "CPU:" | tail -1 | awk -F'usr' '{split($1, vs, " "); v=vs[length(vs)]; printf "%s", v; }'`
  
  ping_check $host_ip
  rtl=$? 
  t1=$(date +%s)
  pingT=$(($t1-$nowT))
  if [ $pingT -gt 15 ]; then
      pingT="$pingT(PING超时)"
  else
      pingT="$pingT(PING正常)"
  fi
  
  pingRet="ping success"
  if [ "$rtl" != "0" ]; then
    pingRet="ping 失败存在丢包情况"
  fi

  sdWT=0
  if [ "$SD_LOG" != "" ]; then
    t1=$(date +%s) 
    echo "[$i][cpu:$cpuv][$sleepT][$pingT]: `date +"%Y-%m-%d %H:%M:%S"` $host_ip $pingRet" >>${SD_LOG} 2>&1
    t2=$(date +%s)  
    sdWT=$(($t2-$t1))
    if [ $sdWT -gt 2 ]; then
      sdWT="$sdWT(SD超时)"
    else
      sdWT="$sdWT(SD正常)"
    fi
  fi
 
  echo "[$i][cpu:$cpuv][$sleepT][$pingT][$sdWT]: `date +"%Y-%m-%d %H:%M:%S"` $host_ip $pingRet" >>${MONITOR_LOG} 2>&1
  let i++
  lastT=$(date +%s)
  sleep 60s
done  