#!/bin/bash

# script/setup: Set up container for the first time after cloning

set -e

cd "$(dirname "$0")/.."

source version

script/bootstrap

echo "==> Setting up container postgres"
if podman container exists postgres; then
    if podman ps -q --filter "name=postgres"; then
        echo "  => postgres is running"
    fi
else
    if podman secret exists pg_password; then
        echo "  => secret exists"
    else
        echo "kontor" | podman secret create pg_password -
    fi
    podman run -d --replace --pod kontor --name postgres \
        --secret source=pg_password,type=env,target=POSTGRES_PASSWORD \
        -e POSTGRES_DB=kontor \
        -e POSTGRES_USER=kontor \
	-e POSTGRES_HOST_AUTH_METHOD=scram-sha-256 \
        -v kontor-db:/var/lib/postgresql/data \
        --health-cmd='pg_isready -U kontor || exit 1' \
        --health-interval=1s \
        --health-timeout=5s \
        --health-retries=10 \
        docker.io/library/postgres:17
fi

echo "==> Setting up container adminer"
if podman container exists adminer; then
    if podman ps -q --filter "name=adminer"; then
        echo "  => adminer is running"
    fi
else
    podman run -d --replace --pod kontor --name adminer docker.io/library/adminer
fi


echo "==> Setting up container pgadmin"
if podman container exists pgadmin; then
    if podman ps -q --filter "name=pgadmin"; then
        echo "  => pgadmin is running"
    fi
else
    podman run -d --replace --pod kontor --name pgadmin \
        -e 'PGADMIN_DEFAULT_EMAIL=thomas.peetz@thpeetz.de' \
	-e 'PGADMIN_DEFAULT_PASSWORD=kontor' \
	docker.io/dpage/pgadmin4:latest
fi

