#!/bin/bash

LOCATION="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

CONF_FILE=${LOCATION}/instances.conf
INSTANCES_DIR=${LOCATION}/instances
COMPOSE_FILE=${LOCATION}/docker-compose.yml
ENV_TEMPLATE=${LOCATION}/template.env

echo "starting all instances"

if [ ! -f "${CONF_FILE}" ]; then
  echo "missing conf file: ${CONF_FILE}"
  exit 1
fi

echo "processing config file: ${CONF_FILE}"

# load instance names and port numbers from conf file
instances=($(sed -n "s/INSTANCES=//p" ${CONF_FILE}))
ports=($(sed -n "s/APP_PORTS=//p" ${CONF_FILE}))
for ((i=0;i<${#instances[@]};i++)); do

  # prepare directory and config files for instance
  instance=$(echo ${instances[$i]} | tr -d '"')
  port=$(echo ${ports[$i]} | tr -d '"')
  echo
  echo "configuring instance $((i+1)) / ${#instances[@]}"
  echo "  name: ${instance}"
  echo "  port: ${port}"
  mkdir -p ${INSTANCES_DIR}/${instance}/data
  sed -e "s/{{INSTANCE_NAME}}/${instance}/g" -e "s/{{INSTANCE_PORT}}/${port}/g" ${ENV_TEMPLATE} > ${INSTANCES_DIR}/${instance}/.env
  cp ${COMPOSE_FILE} ${INSTANCES_DIR}/${instance}/

  # start app
  pushd ${INSTANCES_DIR}/${instance} > /dev/null
  docker compose up -d --force-recreate
  popd > /dev/null
done

echo "done."