#!/usr/bin/env bash
# ============================================================================
# Evony Mesh — control central.  Uso:
#   meshctl.sh {start|stop|restart|start-window|status} {all|hub|lume|dasea|niteman|2xs|rex|valk}
# Los .command (raíz + carpetas por nodo) son atajos que llaman aquí.
# Relleno de rallies:  MESH_FILL=1 meshctl.sh start <nodo>
# ============================================================================
DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=_common.sh
source "$DIR/_common.sh"

action="$1"; target="$2"
usage(){ echo "uso: meshctl.sh {start|stop|restart|start-window|status} {all|hub|$(all_ids | paste -sd'|' -)}"; }

do_one(){ # <action> <target>
  case "$2" in
    hub) case "$1" in start) start_hub;; stop) stop_hub;; restart) stop_hub; sleep 2; start_hub;; start-window) start_hub;; esac;;
    *)   case "$1" in
           start)        start_node "$2";;
           start-window) start_node_window "$2";;
           stop)         stop_node "$2";;
           restart)      stop_node "$2"; sleep 2; start_node "$2";;
         esac;;
  esac
}

case "$action" in
  start|stop|restart|start-window)
    if [ "$target" = "all" ]; then
      if [ "$action" = "restart" ]; then
        restart_all_staggered                       # ESCALONADO: uno a uno (evita kicks del restart simultáneo)
      elif [ "$action" = "stop" ]; then
        for id in $(all_ids); do do_one stop "$id"; done
        do_one stop hub
        echo; status_all
      else
        do_one start hub                            # hub primero (los nodos le hablan)
        for id in $(all_ids); do do_one "$action" "$id"; done
        echo; status_all
      fi
    elif [ -n "$target" ]; then
      do_one "$action" "$target"
    else
      usage
    fi
    ;;
  status|"") status_all ;;
  *) usage ;;
esac
