#!/bin/bash

#Ki: François
#Kan: 2021
#Koi: gestion des réseaux docker

#15/01/2025: Dernière modif by fab: connecter le réseau de l'orga nouvellement créé au ocntainter Traefik

# faire un completion avec les composant dispo

PRG=$(basename $0)

KAZ_ROOT=$(cd "$(dirname $0)/.."; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars

usage () {
    echo "Usage: ${PRG} [-n] [-h] list|add [netName]..."
    echo "    -n         : simulation"
    echo "    -h|--help  : help"
    echo
    echo "    create all net : ${PRG} add $(${KAZ_BIN_DIR}/kazList.sh compose validate)"
    exit 1
}

allNetName=""
export CMD=""
for ARG in $@; do
    case "${ARG}" in
	'-h' | '-help' )
	    usage
	    ;;
	'-n' )
	    shift
	    export SIMU="echo"
	    ;;
	-*)
	    usage
	    ;;
	list|add)
	    CMD="${ARG}"
	    shift;
	    ;;
	*)
	    allNetName="${allNetName} ${ARG}"
	    shift
	    ;;
    esac
done

if [ -z "${CMD}" ] ; then
    usage
fi

# running composes
export allBridgeName="$(docker network list | grep bridge | awk '{print $2}')"
# running network
export allBridgeNet=$(for net in ${allBridgeName} ; do docker inspect ${net} | grep Subnet | sed 's#.*"\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/[0-9]*\)".*# \1#'; done)

minB=0
minC=0
minD=0

getNet() {
    netName="$1Net"

    if [[ "${allBridgeName}" =~ "${netName}" ]]; then
	echo "${netName} already created"
	return
    fi
    # echo "start 10.${minB}.${minC}.$((${minD}*16))"

    find=""
    for b in  $(eval echo {${minB}..255}); do
	for c in $(eval echo {${minC}..255}); do
	    for d in $(eval echo {${minD}..15}); do
		if [ ! -z "${find}" ]; then
		    minB=${b}
		    minC=${c}
		    minD=${d}
		    return
		fi
		# to try
		subnet="10.${b}.${c}.$((d*16))"
		if [[ "${allBridgeNet}" =~ " ${subnet}/" ]];
		then
		    # used
		    # XXX check netmask
		    continue
		fi
		# the winner is...
		echo "${netName} => ${subnet}/28"
		${SIMU} docker network create --subnet "${subnet}/28" "${netName}"
		
		#maj du 15/01 by fab (pour éviter de restart le traefik)
		${SIMU} docker network connect "${netName}" traefikServ
		
		find="ok"
	    done
	    minD=0
	done
	minC=0
    done
}

list () {
    echo "name: " ${allBridgeName}
    echo "net: " ${allBridgeNet}
}

add () {
    if [ -z "${allNetName}" ] ; then
	usage
    fi
    for netName in ${allNetName}; do
	getNet "${netName}"
    done
}

"${CMD}"
