#!/usr/bin/env bash
# c-dev: dispatcher for the CARE workspace docker stacks.
# Usage:
#   c-dev <service> <action> [extra args forwarded to docker compose]
#     service: all | mem | plat
#     action:  up | down | ps | logs | restart
#
# Environment:
#   CARE_WORKSPACE   prepared workspace dir
#                    (default: ~/Development/care-workspace)
#
# The wrapper scripts in the same directory (c-up, c-mem-logs, ...)
# all delegate here.

set -euo pipefail

# Resolve the real script dir, following any symlinks the user installed
# under ~/.local/bin or similar.
src="${BASH_SOURCE[0]}"
while [ -L "$src" ]; do
  dir="$(cd -P "$(dirname "$src")" >/dev/null && pwd)"
  src="$(readlink "$src")"
  [[ $src != /* ]] && src="$dir/$src"
done
SCRIPT_DIR="$(cd -P "$(dirname "$src")" >/dev/null && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"

WORKSPACE="${CARE_WORKSPACE:-$HOME/Development/care-workspace}"

usage() {
  cat >&2 <<'EOF'
usage: c-dev <service> <action> [args...]
  service: all | mem | plat
  action:  up | down | ps | logs | restart

env:
  CARE_WORKSPACE   path to the prepared workspace
                   (default: ~/Development/care-workspace)
EOF
  exit 2
}

[ $# -ge 2 ] || usage
service="$1"
action="$2"
shift 2

case "$service" in
  all)  only=() ;;
  mem)  only=(--only gigaevo-memory) ;;
  plat) only=(--only gigaevo-platform) ;;
  *)    echo "c-dev: unknown service '$service'" >&2; usage ;;
esac

case "$action" in
  up|down|ps|logs|restart) ;;
  *) echo "c-dev: unknown action '$action'" >&2; usage ;;
esac

exec uv run "$REPO_DIR/services.py" "$WORKSPACE" "$action" "${only[@]}" "$@"
