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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUN_STACK_SCRIPT="$ROOT_DIR/scripts/run-stack.sh"
NGROK_URL="${NGROK_URL:-https://comparatuvehiculo.ngrok.io}"
APP_MATCH=".output/server/index.mjs"

is_app_running() {
  ps -eo args= | grep -F "$APP_MATCH" | grep -Fv "grep" >/dev/null 2>&1
}

is_ngrok_running() {
  ps -eo args= | awk -v url="$NGROK_URL" '$0 ~ /ngrok http/ && index($0, url) { found=1 } END { exit(found ? 0 : 1) }'
}

is_stack_launcher_running() {
  pgrep -af "$RUN_STACK_SCRIPT" >/dev/null 2>&1
}

start_with_user_systemd() {
  if ! command -v systemctl >/dev/null 2>&1; then
    return 1
  fi

  if systemctl --user is-active --quiet comp-autos.service >/dev/null 2>&1; then
    return 0
  fi

  systemctl --user start comp-autos.service >/dev/null 2>&1
}

if is_app_running && is_ngrok_running; then
  exit 0
fi

if is_stack_launcher_running; then
  exit 0
fi

if start_with_user_systemd; then
  echo "comp-autos.service iniciado por watchdog"
  exit 0
fi

nohup /usr/bin/env bash "$RUN_STACK_SCRIPT" >/tmp/comp_autos_watchdog_launch.log 2>&1 &
sleep 2

if is_stack_launcher_running; then
  echo "run-stack.sh iniciado por watchdog"
  exit 0
fi

echo "No se pudo iniciar el stack automaticamente." >&2
exit 1
