#!/bin/bash
# -c 包总数 -i 默认每1秒发送 -W 3秒后停止

time=`date "+%Y-%m-%d %H:%M:%S"`
downFile=/data/edgeBox/shell/down
logFile=/data/edgeBox/shell/ping.log

if [ ! -d "/data/edgeBox/shell" ]; then
  mkdir -pv /data/edgeBox/shell
fi

if [ ! -f ${downFile} ]; then
  touch ${downFile}
fi

if [ ! -f ${logFile} ]; then
  touch ${logFile}
fi

getDownNum(){
  local downNum=0
  if [ -f ${downFile} ]; then
    downNum=`cat ${downFile}|wc -l`
  fi
  echo "${time} downNum is ${downNum} ." >> ${logFile}
  if [ $downNum -ge 30 ]; then
     :> ${downFile}
     echo "init 6......"
     echo "${time} init 6......" >> ${logFile}
     /bin/sh -c  '/sbin/reboot'
  fi
}

cleanLog(){
  local lineNum=0
  if [ -f ${logFile} ]; then
    lineNum=`cat ${logFile}|wc -l`
  fi
  if [ $lineNum -ge 5000 ]; then
    :> ${logFile}
  fi
}

pingTest(){
  echo "pingTest..."
  local pingStatus="1"

  ping -c 3 -i 0.2 -W 3 www.wesais.com &>/dev/null
  if [ $? -eq 0  ]; then
      pingStatus=$pingStatus"2"
  fi

  ping -c 3 -i 0.2 -W 3 baidu.com &>/dev/null
  if [ $? -eq 0  ]; then
      pingStatus=$pingStatus"3"
  fi

  ping -c 3 -i 0.2 -W 3 116.62.203.20 &>/dev/null
  if [ $? -eq 0  ]; then
      pingStatus=$pingStatus"4"
  fi


  echo "${time} ping status: $pingStatus"
  echo "${time} $pingStatus" >> ${logFile}

  if [ "$pingStatus"x = "1"x ]
    then
      echo "${time} Host PONG is down" >> ${downFile}
      getDownNum
      #ifdown enp1s0
      #sleep 2
      #ifup enp1s0
    else
      :> ${downFile}
      cleanLog
  fi

}

if [ -f /data/edgeBox/setRouteDo.sh ]; then
  /bin/sh -c  '/data/edgeBox/setRouteDo.sh'
fi

pingTest

