#!/bin/bash
set -euo pipefail
INSTALL_DIR="/opt/morpheus-worker"
RECONFIGURE_SCRIPT="$INSTALL_DIR/bin/reconfigure.sh"
usage() {
  cat <<EOF
Usage: morpheus-worker-ctl COMMAND
Commands:
  reconfigure    Regenerate configuration and restart services
  start          Start all services
  stop           Stop all services
  restart        Restart all services
  status         Show status of all services
  tail           Tail all log files
  show-config    Display current configuration values
  help           Show this help message
EOF
}
cmd_reconfigure() { exec bash "$RECONFIGURE_SCRIPT"; }
cmd_start() {
  systemctl start morpheus-worker-worker
  systemctl start morpheus-worker-nginx
  systemctl is-enabled morpheus-worker-guacd &>/dev/null 2>&1 && systemctl start morpheus-worker-guacd
  echo "All Morpheus Worker services started."
}
cmd_stop() {
  systemctl stop morpheus-worker-nginx 2>/dev/null || true
  systemctl stop morpheus-worker-worker 2>/dev/null || true
  systemctl stop morpheus-worker-guacd 2>/dev/null || true
  echo "All Morpheus Worker services stopped."
}
cmd_restart() { cmd_stop; cmd_start; }
cmd_status() {
  echo "=== Worker ==="; systemctl status morpheus-worker-worker --no-pager 2>/dev/null || echo "not running"; echo ""
  echo "=== Nginx ==="; systemctl status morpheus-worker-nginx --no-pager 2>/dev/null || echo "not running"; echo ""
  echo "=== Guacd ==="; systemctl status morpheus-worker-guacd --no-pager 2>/dev/null || echo "not installed or not running"
}
cmd_tail() { tail -f /var/log/morpheus-worker/worker/current /var/log/morpheus-worker/nginx/*.log 2>/dev/null; }
cmd_show_config() {
  [[ -f /etc/morpheus/morpheus-worker.rb ]] && { echo "=== /etc/morpheus/morpheus-worker.rb ==="; cat /etc/morpheus/morpheus-worker.rb; } || echo "No config found"
  echo ""; [[ -f "$INSTALL_DIR/conf/application.yml" ]] && { echo "=== $INSTALL_DIR/conf/application.yml ==="; cat "$INSTALL_DIR/conf/application.yml"; }
}
case "${1:-help}" in
  reconfigure) cmd_reconfigure ;; start) cmd_start ;; stop) cmd_stop ;; restart) cmd_restart ;;
  status) cmd_status ;; tail) cmd_tail ;; show-config) cmd_show_config ;; help|--help|-h) usage ;;
  *) echo "Unknown command: $1"; usage; exit 1 ;;
esac
