#!/usr/bin/env bash # stop-server.sh — detiene el servidor web registrado en .run/server.info. # Espejo de scripts/stop-server.ps1 (Windows). Mensajes en espanol como el .ps1. # # Uso: bash scripts/stop-server.sh (o `make stop`) # Compatible con el bash 3.2 de macOS y con POSIX sh. set -u SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" || exit 1 ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" || exit 1 cd "$ROOT" || exit 1 INFO_FILE=".run/server.info" say() { printf '%s\n' "$*"; } # --- algo sigue escuchando en el puerto? (nc, con fallback a python3) --- port_busy() { # $1 = puerto; exit 0 si hay un proceso aceptando conexiones ahi if command -v nc >/dev/null 2>&1; then nc -z 127.0.0.1 "$1" >/dev/null 2>&1 elif command -v python3 >/dev/null 2>&1; then python3 - "$1" <<'PYEOF' >/dev/null 2>&1 import socket, sys s = socket.socket() s.settimeout(1) try: s.connect(("127.0.0.1", int(sys.argv[1]))) except OSError: sys.exit(1) PYEOF else return 1 fi } say "" if [ ! -f "$INFO_FILE" ]; then say " [yt-scraper] no hay servidor registrado; nada que detener." say " [ok] nada que detener." say "" exit 0 fi first_line="$(head -n 1 "$INFO_FILE" 2>/dev/null || true)" # primera linea: "PUERTO PID FECHA" set -- $first_line PORT="${1:-}" PIDV="${2:-}" say " [yt-scraper] Apagando el servidor..." # PID ausente, no-numerico o ya muerto -> ya estaba apagado. if [ -z "$PIDV" ]; then say " [info] El servidor ya estaba apagado." else case "$PIDV" in *[!0-9]* | "") say " [info] registro corrupto; solo limpio el archivo." ;; *) if ! kill -0 "$PIDV" 2>/dev/null; then say " [info] El servidor ya estaba apagado." else # kill amable, ~4 s de gracia y luego kill -9. kill "$PIDV" 2>/dev/null i=0 while [ "$i" -lt 10 ] && kill -0 "$PIDV" 2>/dev/null; do sleep 0.4 i=$((i + 1)) done if kill -0 "$PIDV" 2>/dev/null; then say " [kill] no cerro solo; forzando (kill -9)..." kill -9 "$PIDV" 2>/dev/null sleep 0.5 fi fi ;; esac fi rm -f "$INFO_FILE" if [ -n "$PORT" ] && port_busy "$PORT"; then say " [warn] Algo sigue ocupando el puerto $PORT. Revisa con: lsof -i :$PORT" else say " [ok] puerto liberado, servidor detenido." fi say ""