#!/usr/bin/env bash
# bin/railiance — Rails-style CLI entrypoint for Railiance
set -euo pipefail

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

usage() {
  cat <<'EOF'
Usage: bin/railiance <command>

Commands:
  next          Show canonical first-time sequence
  doctor        Check local prerequisites (git, curl, jq, ansible)
  plan-host     Print provider-neutral host specs & checklist
  gen-ssh-key   Generate an SSH key (ed25519) and print pubkey
  cloudinit     Emit minimal cloud-init user-data
  init-repo     Idempotently furnish repo housekeeping
  build-spore   Build a distributable "Spore" bundle
  seed-local    Run the seed script on this machine
  checklist     Print a pre-VM checklist
  help          Show this help
EOF
}

cmd="${1:-help}"

need(){ command -v "$1" >/dev/null 2>&1 || { echo "Missing: $1" >&2; exit 1; }; }

case "$cmd" in
  help) usage ;;
  next) cat "$ROOT/docs/first_host.md" ;;
  doctor)
    for c in git curl jq; do
      command -v "$c" >/dev/null && echo "OK: $c" || { echo "Missing: $c"; exit 1; }
    done
    command -v ansible >/dev/null && echo "OK: ansible" || echo "Note: ansible not found (only needed for host bootstrap)"
    ;;
  plan-host)
    sed -n '1,200p' "$ROOT/docs/first_host.md" | sed -n '/^## 2\) Choose/,/^## 3\)/p'
    ;;
  gen-ssh-key)
    need ssh-keygen
    key="${HOME}/.ssh/id_ed25519"
    [[ -f "$key" ]] || ssh-keygen -t ed25519 -N "" -f "$key"
    echo "Public key:"
    cat "${key}.pub"
    ;;
  cloudinit) cat "$ROOT/cloudinit/user-data.yaml" ;;
  init-repo) bash "$ROOT/tools/furnish_railiance_repo.sh" ;;
  build-spore) bash "$ROOT/tools/build_spore.sh" ;;
  seed-local) bash "$ROOT/tools/seed_node.sh" ;;
  init-inventory) 
    if [[ -f "$ROOT/ansible/hosts.ini" ]]; then
      echo "ansible/hosts.ini already exists."
    else
      cp "$ROOT/ansible/hosts.ini.example" "$ROOT/ansible/hosts.ini"
      echo "Created ansible/hosts.ini from example."
    fi
    ;;
  checklist)
    cat <<'CK'
Rent-a-VM Checklist
-------------------
[ ] Provider account ready (billing set)
[ ] Region chosen (low latency to you/users)
[ ] Image: Ubuntu 24.04 LTS
[ ] Size: 2 vCPU / 4–8 GB RAM / 60+ GB SSD
[ ] SSH key uploaded (see gen-ssh-key)
   - Run: bin/railiance gen-ssh-key
[ ] Cloud-init pasted (see: bin/railiance cloudinit)
[ ] Hostname set (e.g., railiance-seed-1)
[ ] Record public IP / DNS
CK
    ;;
  *) usage; exit 2 ;;
esac
