#!/bin/bash -ex
#trap "echo Booh!" SIGINT

export DOCKER_HOST=dkmanager:2376

DKREGISTRY=dkregistry.xai-corp.net:5000
CONFIG=stack.tmp.yml
SERVICE=services
#NETWORK=prod

scale_out() {
    REPLICA_COUNT=`docker service inspect $1 | jq '.[0].Spec.Mode.Replicated.Replicas'`
    ./timeout.sh -t $2 docker service scale $1=$(($REPLICA_COUNT*2))
    ./timeout.sh -t $2 docker service scale $1=$(($REPLICA_COUNT))
    ./timeout.sh -t $2 docker service update -q $1
}

#docker stack deploy -c dkregistry/docker-compose.yml $SERVICE
#docker service update -q services_registry
< ../password.txt docker login --username richard --password-stdin $DKREGISTRY

docker-compose \
    -f network.yml \
    -f postgres/docker-compose.yml \
    -f mariadb/docker-compose.yml \
    -f fluentd/docker-compose-prod.yml \
    -f memcached/docker-compose.yml \
    -f redis/docker-compose.yml \
    -f datadog/docker-compose.yml \
    -f cron/docker-compose.yml \
    config > $CONFIG


#    -f dkregistry/docker-compose.yml \

docker stack deploy --with-registry-auth -c $CONFIG $SERVICE

# Cleanup
rm $CONFIG

#scale_out services_registry 60
scale_out services_postgres 60 &
scale_out services_mysql 60 &
scale_out services_memcached 60 &
scale_out services_redis 60 &
#scale_out services_fluentd 120 &
#scale_out services_datadog 60 &
scale_out services_cron 60 &
scale_out services_letsencrypt_updates 60 &

wait
echo "All done."
