#!/bin/bash
# 用于添加公网IP，并添加内网静态路由,需要在机器本地执行
# author: jabber.zhou
# date: 2024-01-11
 
if [[ $# -lt 1 ]];then
    echo -e "\033[32m Usage: $0 IP/mask [ethX] \033[0m"
    exit 1
fi
 
ipcalc -c $1
if [[ $? -ne 0 ]]; then
    echo "Validate IP address $1 failed"
    exit 1
fi
 
PUB_ETH=$2
if [[ -z $PUB_ETH ]];then
    PUB_ETH=eth1
fi
 
ethtool $PUB_ETH 1>/dev/null
if [[ $? -ne 0 ]];then
    echo "netcard '$PUB_ETH' not exist!"
    exit 2
fi
 
ipaddr=`echo $1|cut -f1 -d'/'`
nm=`echo $1|cut -f2 -d'/'`
netmask=`ipcalc -m $ipaddr/$nm|awk -F '=' '{print $2}'`
ga1=`ipcalc -n $ipaddr/$nm|awk -F '=' '{print $2}'|awk -F '.' '{print $1"."$2"."$3}'`
ga2=`ipcalc -n $ipaddr/$nm|awk -F '=' '{print $2}'|awk -F '.' '{print $4}'`
if [[ -z $ga1 || -z $ga2 ]];then
    echo "Validate IP address $1 failed"
    exit 1
fi
ga3=$(($ga2 + 1))
gateway="$ga1.$ga3"
 
# Get IP Address
 
JP='192.168.168.106'
 
MAN_IP=`ip -o r get $JP|sed -n 's/.*src \([0-9.]*\) .*/\1/p'`
if [[ -z $MAN_IP ]];then
    echo "can not get MAN_IP"
    exit 1
fi
 
MAN_ETH=`ip -o r get $JP |sed -n 's/.*dev \([a-z0-9]*\) .*/\1/p'`
if [[ -z $MAN_ETH ]];then
    echo "can not get MAN_ETH"
    exit 1
fi
 
MAN_gateway=`ip -o r get $JP|sed -n 's/.*via \([0-9\.]*\).*/\1/p'`
if [[ -z $MAN_gateway ]];then
    echo "can not get MAN_gateway"
    exit 1
fi
 
# do
 
# add route
routes="172.16.0.0/12 192.168.0.0/16 10.0.0.0/8 100.96.0.0/11"
route_file=/etc/sysconfig/network-scripts/route-$MAN_ETH
for route in $routes;do
    if [[ $(grep -c "$route" $route_file 2>/null) -eq 0 ]];then
        echo "$route via $MAN_gateway" >> /etc/sysconfig/network-scripts/route-$MAN_ETH
        ip r add $route via $MAN_gateway
    fi
done
 
sed -i '/GATEWAY/d' /etc/sysconfig/network-scripts/ifcfg-$MAN_ETH
ip r del default
 
cat > /etc/sysconfig/network-scripts/ifcfg-$PUB_ETH <<EOF
DEVICE=$PUB_ETH
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=static
IPADDR=$ipaddr
NETMASK=$netmask
GATEWAY=$gateway
EOF
ifup $PUB_ETH
 
sleep 5

GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

dns_list=("8.8.8.8" "119.29.29.29" "223.5.5.5" "1.1.1.1" "1.2.4.8")
success_count=0

for i in "${dns_list[@]}"; do
    if ping -w3 -c1 "$i"; then
        echo -e "${GREEN}ping ${i} successful${NC}"
        success_count=$((success_count + 1))
    fi
done

if (( "$success_count" > 1 )); then
    echo -e "${GREEN}ping check successful${success_count}${NC}"
else
    echo -e "${RED}ping check failed${NC}"
    exit 3
fi

