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

APP_DIR="{{ app_dir }}"
COMPOSE_FILE="$APP_DIR/compose.yml"
ENV_FILE="$APP_DIR/.env"
PROJECT="arche"
PODMAN_READY_ATTEMPTS=6
PODMAN_READY_DELAY_SECONDS=5

wait_for_podman() {
  local attempt=1

  while [ "$attempt" -le "$PODMAN_READY_ATTEMPTS" ]; do
    if podman info >/dev/null 2>&1; then
      return 0
    fi

    if [ "$attempt" -lt "$PODMAN_READY_ATTEMPTS" ]; then
      sleep "$PODMAN_READY_DELAY_SECONDS"
    fi

    attempt=$((attempt + 1))
  done

  printf 'podman is not ready after %s attempts\n' "$PODMAN_READY_ATTEMPTS" >&2
  return 1
}

compose() {
  if podman compose version >/dev/null 2>&1; then
    podman compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" -p "$PROJECT" "$@"
    return
  fi

  podman-compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" -p "$PROJECT" "$@"
}

start_container_if_needed() {
  local container_id="$1"

  if [ -z "$container_id" ]; then
    return 0
  fi

  if [ -n "$(podman ps -q --filter id="$container_id")" ]; then
    return 0
  fi

  podman start "$container_id"
}

current_web_container_ids() {
  local current_version=""

  if [ -s "$APP_DIR/.current-version" ]; then
    current_version="$(tr -d '[:space:]' < "$APP_DIR/.current-version")"
  fi

  if [ -z "$current_version" ]; then
    printf 'missing or empty %s/.current-version; refusing to autostart unknown web containers\n' "$APP_DIR" >&2
    return 1
  fi

  podman ps -a -q --filter label=arche.role=web --filter label="arche.version=$current_version"
}

wait_for_podman

compose up -d postgres traefik docker-socket-proxy{% if exposure_mode == 'cloudflare-tunnel' %} cloudflared{% endif %}{% if deploy_mode == 'remote' %} reaper flows{% endif %}

# Web and workspace containers are managed outside compose.
web_container_ids="$(current_web_container_ids)"
workspace_container_ids="$(podman ps -a -q --filter label=arche.managed=true)"

while IFS= read -r container_id; do
  start_container_if_needed "$container_id"
done < <(
  {
    printf '%s\n' "$web_container_ids"
    printf '%s\n' "$workspace_container_ids"
  } | sort -u
)
