#!/bin/bash
DAEMON_FILE=/etc/docker/daemon.json

if [ $# -eq 0 ];then
    echo "Usage $0 -d docker0 network -g docker_gwbridge network"
    exit 1
fi

while getopts "d:g:" arg
do 
   case $arg in
       d) 
         DOCKER0_NETWORK=${OPTARG}
         ;;
       g)
         GWBRIDGE_NETWORK=${OPTARG}
         ;;
       *)
         echo "Usage $0 -d docker0 network -g docker_gwbridge network"
         exit 1
        ;;
    esac
done


clear_bridge(){
    systemctl stop docker
    ip link set docker0 down  && ip link del dev docker0
    ip link set docker_gwbridge down && ip link del dev docker_gwbridge
    rm -rf /var/lib/docker/swarm
    rm -rf /var/lib/docker/network

}

config_daemon(){
    if [ -f "${DAEMON_FILE}" ];then
       sed -i /bip/d "${DAEMON_FILE}"
       sed -i "1a\"bip\": \"${DOCKER0_NETWORK}\"," ${DAEMON_FILE}
       sed -i /default-address-pools/d ${DAEMON_FILE}
       sed -i "2a\"default-address-pools\": [{\"base\":\"${GWBRIDGE_NETWORK}\",\"size\":24}]," ${DAEMON_FILE}
       sed -i /^$/d ${DAEMON_FILE}
       TOTAL_NUM=$(wc -l ${DAEMON_FILE})
       NUM=$(($(wc -l ${DAEMON_FILE}|awk '{print $1}')-1))
       sed -i "${NUM}s/\,$//g" ${DAEMON_FILE}
    else   
       mkdir /etc/docker -p
      cat > /etc/docker/daemon.json <<EOF
{
  "bip": "${DOCKER0_NETWORK}",
  "default-address-pools": [{"base":"${GWBRIDGE_NETWORK}","size":24}]
}
EOF
    fi 
}

main(){
clear_bridge
config_daemon
systemctl restart docker
}

main

