#!/usr/bin/env bash
# deckctl — overdeck AI OS control CLI (fail-closed dispatcher).
set -euo pipefail

DECKCTL_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

usage() {
  echo "usage: deckctl <bootstrap|doctor|status|sync|install|units|agents|fleet> [...]" >&2
  exit 2
}

die() {
  echo "deckctl: ERROR: $*" >&2
  exit 1
}

[[ $# -ge 1 ]] || usage

cmd="$1"
shift

case "$cmd" in
  bootstrap|doctor|status|sync|install|units|agents|fleet) ;;
  *) usage ;;
esac

if [[ "$cmd" == "fleet" ]]; then
  DECKCTL_PROJECT_ROOT="$(git -C "$PWD" rev-parse --show-toplevel 2>/dev/null)" \
    || die "fleet must run from inside a Git checkout"
  export DECKCTL_PROJECT_ROOT
fi

lib="$DECKCTL_ROOT/lib/deckctl/${cmd}.sh"
[[ -f "$lib" ]] || die "subcommand '$cmd' is not installed ($lib missing)"

# shellcheck source=/dev/null
source "$lib"

fn="cmd_${cmd}"
declare -f "$fn" >/dev/null 2>&1 || die "subcommand '$cmd' is not implemented"

"$fn" "$@"
