#!/usr/bin/env bash
set -euo pipefail

#  — Configura aquí si hace falta —
SERVICE_NAME="consumer-service"
EXECUTABLE="$(pwd)/${SERVICE_NAME}"
PID_FILE="$(pwd)/${SERVICE_NAME}.pid"
LOG_FILE="$(pwd)/${SERVICE_NAME}.log"
#  — fin de configuración —


function start() {
  if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" &>/dev/null; then
    echo "⚠️  ${SERVICE_NAME} ya está corriendo (PID=$(cat $PID_FILE))."
    exit 1
  fi

  echo "🚀 Iniciando ${SERVICE_NAME} en segundo plano..."
  nohup "$EXECUTABLE" > "$LOG_FILE" 2>&1 &
  echo $! > "$PID_FILE"
  echo "   → PID registrado en $PID_FILE"
  echo "   → Logs en $LOG_FILE"
}

function stop() {
  if [ ! -f "$PID_FILE" ]; then
    echo "⚠️  No hay PID file ($PID_FILE), ¿ya lo detuviste?"
    exit 1
  fi

  PID=$(cat "$PID_FILE")
  echo "🛑 Deteniendo ${SERVICE_NAME} (PID=$PID)..."
  kill "$PID" && sleep 2

  if kill -0 "$PID" &>/dev/null; then
    echo "   ❗ No respondió, forzando..."
    kill -9 "$PID"
  fi

  rm -f "$PID_FILE"
  echo "   → Detenido y PID file borrado."
}

function status() {
  if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" &>/dev/null; then
    echo "✅  ${SERVICE_NAME} está corriendo (PID=$(cat $PID_FILE))."
  else
    echo "❌  ${SERVICE_NAME} NO está corriendo."
  fi
}

case "${1:-}" in
  start)   start ;;
  stop)    stop ;;
  restart) stop && start ;;
  status)  status ;;
  *)
    echo "Uso: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac
