#!/bin/bash
# 用于添加公网IP，并添加内网静态路由,需要在机器本地执行
# author: jabber.zhou
# date: 2020-06-19

if [[ $# -lt 1 ]];then
    echo -e "\033[32m Usage: $0 IP/mask [ethX] \033[0m"
    exit 1
fi

ipcalc -6 -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

which subnetcalc
if [[ $? -ne 0 ]];then
    yum -y install subnetcalc
fi

ipaddr=`echo $1|cut -f1 -d'/'`
nm=`echo $1|cut -f2 -d'/'`
gateway=`subnetcalc $1|sed -n 's/Host Range.*{\s\([0-9a-f:]*\)\s-.*/\1/p'`

if [[ -z $gateway ]];then
    echo 'can not get gateway'
    exit 1
fi

# 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

MAN_IPV6=2002:`echo "${MAN_IP}" |awk -F '.' '{printf "%02x%02x:%02x%02x\n",$1,$2,$3,$4}'`::1

# do

# add route
routes="2002:ac10::/28 2002:c0a8::/32 2002:a00::/24 2002:6460::/27"
route_file=/etc/sysconfig/network-scripts/route6-sit6to4
for route in $routes;do
    if [[ $(grep -c "$route" $route_file 2>/null) -eq 0 ]];then
        echo "$route dev sit6to4 src $MAN_IPV6 metric 8" >> $route_file
        ip -6 r add $route dev sit6to4 src $MAN_IPV6 metric 8
    fi
done

grep -q "^IPADDR" /etc/sysconfig/network-scripts/ifcfg-$PUB_ETH

if [[ $? -eq 0 ]];then
    grep -q "^IPV6ADDR" /etc/sysconfig/network-scripts/ifcfg-$PUB_ETH
    if [[ $? -ne 0 ]];then
        cat >> /etc/sysconfig/network-scripts/ifcfg-$PUB_ETH <<EOF
IPV6INIT=yes
IPV6ADDR=$ipaddr
IPV6_DEFAULTGW=$gateway
EOF
    fi
ip -6 a add $ipaddr/$nm dev $PUB_ETH
ip -6 r add default via $gateway dev $PUB_ETH metric 1
else
    cat > /etc/sysconfig/network-scripts/ifcfg-$PUB_ETH <<EOF
DEVICE=$PUB_ETH
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=static
IPV6INIT=yes
IPV6ADDR=$ipaddr
IPV6_DEFAULTGW=$gateway
EOF
    ifup $PUB_ETH
fi

ping6 -w3 -c1 2400:3200:baba::1
if [[ $? -ne 0 ]];then
    echo "ping check failed"
    exit 3
fi

