#!/usr/bin/env bash

set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
bundle_dir="$(cd "$script_dir/.." && pwd)"
images_dir="$bundle_dir/images"

compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  elif command -v docker-compose >/dev/null 2>&1; then
    docker-compose "$@"
  else
    echo "docker compose or docker-compose is required." >&2
    exit 1
  fi
}

ensure_env_file() {
  if [[ ! -f "$bundle_dir/.env" && -f "$bundle_dir/.env.example" ]]; then
    cp "$bundle_dir/.env.example" "$bundle_dir/.env"
    echo "Created .env from .env.example"
  fi
}

ensure_env_file
set -a
# shellcheck disable=SC1091
source "$bundle_dir/.env"
set +a

if [[ ! -d "$images_dir" ]]; then
  echo "Images directory not found: $images_dir" >&2
  exit 1
fi

shopt -s nullglob
image_archives=("$images_dir"/*.tar)
if (( ${#image_archives[@]} == 0 )); then
  echo "No Docker image archives found in $images_dir" >&2
  exit 1
fi

for image_archive in "${image_archives[@]}"; do
  echo "Loading image: $(basename "$image_archive")"
  docker load -i "$image_archive"
done

if [[ -f "$images_dir/public-images.txt" ]]; then
  echo "Public images are not bundled and will be pulled by docker compose if missing:"
  sed 's/^/  - /' "$images_dir/public-images.txt"
fi

cd "$bundle_dir"
if [[ "${USE_EXTERNAL_INFRA:-false}" == "true" ]]; then
  echo "Using external infrastructure. Starting spring-cloud-config-server only."
  compose up -d spring-cloud-config-server
else
  echo "Starting postgres, kafka and spring-cloud-config-server..."
  compose up -d postgres kafka spring-cloud-config-server
fi

echo "Images imported and base services requested."
