#!/bin/sh

# fetch secrets and write them to their according files
cat $vhr18_db > ../env/vhr18_db.env
cat $vhr18_django > ../env/vhr18_django.env
cat $vhr18_obs > ../env/vhr18_obs.env

cat $emg_db > ../env/emg_db.env
cat $emg_django > ../env/emg_django.env
cat $emg_obs > ../env/emg_obs.env


# use `pvs_testing` bucket instead

sed -i -e 's/emg-data/pvs_testing/g' ../env/emg.env
sed -i -e 's/vhr18-data/pvs_testing/g' ../env/vhr18.env

sed -i -e 's/emg-cache/pvs_testing/g' ../env/emg_obs.env
sed -i -e 's/vhr18-cache/pvs_testing/g' ../env/vhr18_obs.env

# source the env file
set -o allexport
source ../env/emg.env
set +o allexport


mkdir data
docker swarm init
docker network create -d overlay emg-extnet
echo "inside gitlab_test"
echo $OS_PASSWORD
echo $DJANGO_PASSWORD

# creat the docker secrets
printf $OS_PASSWORD_DOWNLOAD | docker secret create OS_PASSWORD_DOWNLOAD -
printf $DJANGO_PASSWORD | docker secret create DJANGO_PASSWORD -
printf $OS_PASSWORD | docker secret create OS_PASSWORD -

# creat docker configs 
printf $sftp_users_emg | docker config create sftp_users_emg -

docker stack deploy -c ../docker-compose.emg.yml -c ../docker-compose.emg.dev.yml emg-pvs
apk update && apk add bash postgresql-dev gcc python3-dev musl-dev py-pip gdal libffi-dev openssl-dev make
pip3 install -r requirements.txt

./docker-stack-wait.sh -n renderer -n registrar -n preprocessor -n ingestor -n sftp emg-pvs

docker service ls

bash ./registrar_test.sh product_list.csv

if [ $? -ne 0 ]
then
  echo "Failure in tests, logging from services:"
  for service in $(docker service ls --format "{{.Name}}"); do
    echo "Service:  ${service}"
    docker service logs $service
    docker service ps $service --no-trunc
  done  
  exit 1
fi

