#!/usr/bin/env bash

set -euo pipefail

container_name="${SPACEGAME_POSTGRES_CONTAINER:-space-game-postgres}"
image_name="${SPACEGAME_POSTGRES_IMAGE:-postgres:16}"
host_port="${SPACEGAME_POSTGRES_PORT:-5432}"
database_name="${SPACEGAME_POSTGRES_DB:-spacegame}"
database_user="${SPACEGAME_POSTGRES_USER:-spacegame}"
database_password="${SPACEGAME_POSTGRES_PASSWORD:-spacegame}"

if ! command -v docker >/dev/null 2>&1; then
  echo "docker is required but was not found in PATH." >&2
  exit 1
fi

existing_container_id="$(docker ps -aq -f "name=^${container_name}$")"

if [[ -z "${existing_container_id}" ]]; then
  echo "Creating Postgres container '${container_name}'..."
  docker run -d \
    --name "${container_name}" \
    -e POSTGRES_DB="${database_name}" \
    -e POSTGRES_USER="${database_user}" \
    -e POSTGRES_PASSWORD="${database_password}" \
    -p "${host_port}:5432" \
    "${image_name}" >/dev/null
  echo "Postgres container created and started."
else
  running_container_id="$(docker ps -q -f "name=^${container_name}$")"
  if [[ -n "${running_container_id}" ]]; then
    echo "Postgres container '${container_name}' is already running."
  else
    echo "Starting Postgres container '${container_name}'..."
    docker start "${container_name}" >/dev/null
    echo "Postgres container started."
  fi
fi

echo "Connection string:"
echo "Host=127.0.0.1;Port=${host_port};Database=${database_name};Username=${database_user};Password=${database_password}"
