#!/bin/bash

BASEDIR=$PWD

case "$1" in

  create) 

	prefix=${3:+$3-}

	mkdir -p $BASEDIR/${prefix}training-00/config
	
	if [ ! -f $BASEDIR/${prefix}training-00/config/application.properties ]; then	    
		echo "application.admin.password=training" > ${prefix}training-00/config/application.properties
		echo "application.admin.reset=true" >> ${prefix}training-00/config/application.properties
		echo "cache.config.file=ehcache-compact.xml" >> ${prefix}training-00/config/application.properties	
	fi
	
    for i in $(eval echo {01..${2:-10}}); do
    	mkdir -p $BASEDIR/${prefix}training-$i
    done

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

			echo $t
			
			mkdir -p ${BASEDIR}/$t/config
			cp ${BASEDIR}/${prefix}training-00/config/application.properties ${BASEDIR}/$t/config/application.properties
		   
		   	sed "s/${prefix}training-00/$t/g" ${prefix}training-00/docker-compose.yml > $t/docker-compose.yml		   
			if [ -f $BASEDIR/${prefix}training-00/docker-compose.override.yml ]; then
				sed "s/${prefix}training-00/$t/g" ${prefix}training-00/docker-compose.override.yml > $t/docker-compose.override.yml
			fi
		   
        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 usasapp uspsapp
         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] [prefix] 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
