#!/bin/bash

BASEDIR=$PWD

case "$1" in

  create) 
     
     if [ ! -f $BASEDIR/training-00/docker-compose.override.yml ]; then
         echo "no override file in training-00"
         exit 0
     fi
     if [ ! -f $BASEDIR/training-00/config/application.properties ]; then
 	echo "application.admin.password=training" > training-00/config/application.properties
        echo "application.admin.reset=true" >> training-00/config/application.properties
     fi

     for i in $(eval echo {01..${2:-10}}); do
	mkdir -p $BASEDIR/training-$i
     done

     for t in $( ls -d training-* ); do
        if [ ! $t == "training-00" ]; then

           echo $t
           ln -sf ${BASEDIR}/training-00/docker-compose.yml ${BASEDIR}/$t/docker-compose.yml
           mkdir -p ${BASEDIR}/$t/config
           cp ${BASEDIR}/training-00/config/application.properties ${BASEDIR}/$t/config/application.properties
           sed "s/training-00/$t/g" training-00/docker-compose.override.yml > $t/docker-compose.override.yml

        fi 
     done

     ;;

  compose)

     for t in $( ls -d training-* ); do
         cd $BASEDIR/$t
         docker-compose ${*:2}  
     done
     ;;
 
  reset)

     for t in $( ls -d training-* ); do
         cd $BASEDIR/$t

         docker-compose stop
         docker-compose rm -f usasdb uspsdb
         docker-compose up -d usasdb uspsdb
         sleep 30 # delay to allow database startup and restore
         docker-compose up -d
         sleep 60 # delay to prevent overwhelming host

     done
     ;;


  *)
      echo "usage:"
      echo "  create  [n:-10]          creates training-nn configs based on training-00 directory"
      echo "  compose {cmd} [args...]  executes docker compose command on each training instance"
      echo "  reset                    resets training database on each training instance"
   ;;  
esac
echo "done"
cd $BASEDIR
