#!/usr/bin/env bash
# flightlead — set up and run the FlightOps coordinator distro (preview).
#
#   flightlead init [DIR]     copy the coordinator into DIR (default ./flightlead), then bootstrap it
#   flightlead VERB [ARGS]    run bin/VERB.sh of the coordinator in the current directory
#                             (detect, recover, brief, backend, state, watcher, crew-env, flags)
#
# The coordinator is a directory you start a coding agent in; see its AGENTS.md.
set -euo pipefail
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
DISTRO=${FLIGHTLEAD_DISTRO:-$HERE/../share/flightops/flightlead}

usage() { awk 'NR==1{next} /^#/{sub(/^# ?/,"");print;next} {exit}' "$0"; }

case "${1:-}" in
  init)
    target=${2:-flightlead}
    if [ -e "$target" ] && [ -n "$(ls -A -- "$target" 2>/dev/null)" ]; then
      printf 'flightlead: %s already exists and is not empty\n' "$target" >&2
      exit 2
    fi
    [ -f "$DISTRO/AGENTS.md" ] || { printf 'flightlead: the coordinator is not installed in this release\n' >&2; exit 127; }
    mkdir -p -- "$target"
    cp -R -- "$DISTRO/." "$target/"
    # The archive carries no symlinks and no exec bits on data files: restore both.
    ln -sfn AGENTS.md "$target/CLAUDE.md"
    chmod 755 "$target"/bin/*.sh "$target"/tests/*.sh 2>/dev/null || true
    "$target/bin/bootstrap.sh" --quiet
    printf 'Coordinator ready in %s. Start your coding agent there; it reads AGENTS.md.\n' "$target"
    ;;
  -h|--help|"") usage ;;
  *)
    verb=$1; shift
    root=${FLIGHTLEAD_ROOT:-$PWD}
    if [ ! -f "$root/AGENTS.md" ] || [ ! -f "$root/bin/$verb.sh" ]; then
      printf 'flightlead: run this inside a coordinator directory (see: flightlead init DIR); unknown verb or directory: %s\n' "$verb" >&2
      exit 2
    fi
    exec bash "$root/bin/$verb.sh" "$@"
    ;;
esac
