#!/bin/bash
time=`date "+%Y-%m-%d %H:%M:%S"`
logFile=/data/edgeBox/cmd/setRouteDo.log
#读取文件获取主网卡
eth1=`cat /data/edgeBox/network/route.default`
networkPath="/etc/network/interfaces"


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

cleanLog

if [ -z "$eth1" ];then
  echo "${time} 没有设置默认主网卡，退出..." >> ${logFile}
  echo "${time} 没有设置默认主网卡，退出..."
  exit 1
fi

#获取路由信息
eth0=`ip route |awk 'NR==1{print $5}'`
ethGate0=`ip route |awk 'NR==1{print $3}'`

if [ "$eth1"x = "$eth0"x ];then
  echo "${time} 当前主网卡与要设置的默认主网卡相同，退出..." >> ${logFile}
  echo "${time} 当前主网卡与要设置的默认主网卡相同，退出..."
  exit 1
fi

#获取要设置的网卡网关
ethGate1=`sed -n "/auto $eth1/ {n;n;n;n;p}" $networkPath|awk 'NR==1{print $2}'`

if [ -z $ethGate1 ]; then
  echo "${time} dhcp方式，用如下方式获取网关..." >> ${logFile}
  echo "${time} dhcp方式，用如下方式获取网关..."
  ethGate1=`/sbin/dhclient -v $eth1 2>&1 | awk '/^DHCPACK/ { print $5 }'`
  echo "gateway: ${ethGate1}" >> ${logFile}
fi

if [ -z $ethGate1 ]; then
  echo "${time} 没查到网关地址，退出..." >> ${logFile}
  echo "${time} 没查到网关地址，退出..."
  exit 1
else
    ip route del default via $ethGate0 dev $eth0
    ip route add default via $ethGate1 dev $eth1
fi
