#!/usr/bin/env bash
set -euo pipefail

scripts="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd ${scripts}/..

# Run this from marvel2 directory

echo "===== Shutting down previous docker containers, if present"
${scripts}/local_shutdown.sh

version=$(git rev-parse --short HEAD)

restapi_image_tag="marvel2-restapi:$version"
jobz_image_tag="marvel2-jobz:$version"
frontend_image_tag="marvel2-frontend:$version"

echo "..... Creating docker network"
docker network create marvel2

echo "..... Starting DNS proxy server"
docker run -d --rm --hostname dns.mageddo --name dns-proxy-server \
    --network marvel2 \
    -p 5380:5380 \
    -v ${scripts}:/app/conf \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /etc/resolv.conf:/etc/resolv.conf \
    defreitas/dns-proxy-server

echo "..... Starting postgres"
docker run -d --rm --env POSTGRES_HOST_AUTH_METHOD=trust \
    --hostname postgres --name postgres \
    --network marvel2 \
    -p 5433:5432 \
    postgres

# TODO: figure out how to include this as part of the postgres container
sleep 3
psql -h localhost -p 5433 postgres postgres -c "CREATE DATABASE marvel_dev;"

echo "..... Starting $restapi_image_tag"
docker run -d --rm --hostname restapi --name restapi \
    --network marvel2 \
    -p 8180:80 \
    $restapi_image_tag /opt/zoox/start_marvel_restapi.sh --profile local-docker

# Wait for Kong to finish setting up the DB
sleep 5

echo "..... Starting $jobz_image_tag"
docker run -d --rm --hostname jobz --name jobz \
    --network marvel2 \
    --add-host=local-executor:$(hostname -I | cut -d' ' -f1) \
    -p 8085:80 \
    $jobz_image_tag /jobz --host=local --http-port=80

echo "..... Starting $frontend_image_tag"
docker run -d --rm --hostname frontend --name frontend \
    --network marvel2 \
    -p 8090:80 \
    $frontend_image_tag /entrypoint.sh --host=local --http-port=80

docker ps
exit 0
