#!/bin/bash
IMAGE_BASE_NAME="oc-discovery"
DOCKERFILE_PATH="."

docker network create \
  --subnet=172.40.0.0/24 \
  discovery

for i in $(seq ${1:-0} ${2:-3}); do
  NUM=$((i + 1))
  PORT=$((4000 + $NUM))

  IMAGE_NAME="${IMAGE_BASE_NAME}:${NUM}"


  echo "▶ Building image ${IMAGE_NAME} with CONF_NUM=${NUM}"
  docker build \
    --build-arg CONF_NUM=${NUM} \
    -t "${IMAGE_BASE_NAME}_${NUM}" \
    ${DOCKERFILE_PATH}

  docker kill "${IMAGE_BASE_NAME}_${NUM}" | true
  docker rm "${IMAGE_BASE_NAME}_${NUM}" | true

  echo "▶ Running container ${IMAGE_NAME} on port ${PORT}:${PORT}"
  docker run -d \
    --network="${3:-oc}" \
    -p ${PORT}:${PORT} \
    --name "${IMAGE_BASE_NAME}_${NUM}" \
    "${IMAGE_BASE_NAME}_${NUM}"

  docker network connect --ip "172.40.0.${NUM}" discovery "${IMAGE_BASE_NAME}_${NUM}"
done