#!/bin/bash

docker compose up -d

RETRIES=100

until docker container exec postgres psql -U user -d grepfood -c "select 1" > /dev/null 2>&1 || [ "$RETRIES" -eq 0 ]; do
  echo "Waiting for postgres server, $((RETRIES--)) remaining attempts..."
  sleep 1
done

echo "Setup mockup data"
bash -c ./run-init-mockup.sh

echo "Loading environment..."
set -a
source ./.env
set +a

echo "Run API server"
go run . > ./server.log 2>&1 &

echo "wait for api server startup"
until curl http://localhost:8080/version > /dev/null 2>&1 || [ "$RETRIES" -eq 0 ]; do
  echo "Waiting for api server, $((RETRIES--)) remaining attempts..."
  sleep 1
done

bash -c ./tests/run-tests.sh

echo "Terminating server..."
pkill grepfood-server

echo "Server output following:"
echo "-----------------------------"

cat ./server.log

echo "-----------------------------"
echo "End of server output"
docker compose down
docker volume rm postgres
