eight-hourr/scripts/server.sh

126 lines
2.6 KiB
Bash
Raw Permalink Normal View History

2026-07-17 06:55:36 +00:00
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PID_FILE="$ROOT/backend/data/server.pid"
LOG_FILE="$ROOT/backend/data/server.log"
PYTHON="$ROOT/.venv/bin/python"
PORT="8765"
read_port() {
if [ -f "$ROOT/.env" ]; then
local value
value="$(grep -E '^BACKEND_PORT=' "$ROOT/.env" | tail -1 | cut -d= -f2 | tr -d ' \r' || true)"
if [ -n "$value" ]; then
PORT="$value"
fi
fi
}
is_running() {
if [ ! -f "$PID_FILE" ]; then
return 1
fi
local pid
pid="$(cat "$PID_FILE")"
kill -0 "$pid" 2>/dev/null
}
start_server() {
read_port
if [ ! -x "$PYTHON" ]; then
echo "Missing virtualenv. Run: make setup"
exit 1
fi
if is_running; then
echo "Server already running (PID $(cat "$PID_FILE")) — http://localhost:$PORT"
exit 0
fi
mkdir -p "$(dirname "$PID_FILE")"
cd "$ROOT/backend"
PTS_RELOAD=false nohup "$PYTHON" main.py >>"$LOG_FILE" 2>&1 &
echo $! >"$PID_FILE"
sleep 1
if is_running; then
echo "Started PID $(cat "$PID_FILE") — http://localhost:$PORT"
echo "Log: $LOG_FILE"
exit 0
fi
echo "Failed to start server. Check $LOG_FILE"
rm -f "$PID_FILE"
exit 1
}
stop_server() {
read_port
local pid=""
if is_running; then
pid="$(cat "$PID_FILE")"
kill "$pid" 2>/dev/null || true
for _ in 1 2 3 4 5 6 7 8 9 10; do
kill -0 "$pid" 2>/dev/null || break
sleep 0.3
done
if kill -0 "$pid" 2>/dev/null; then
kill -9 "$pid" 2>/dev/null || true
fi
rm -f "$PID_FILE"
echo "Stopped server (PID $pid)"
return 0
fi
rm -f "$PID_FILE"
local pids=""
while IFS= read -r pid; do
[ -n "$pid" ] || continue
local cmd
cmd="$(ps -p "$pid" -o command= 2>/dev/null || true)"
case "$cmd" in
*"$ROOT/backend"*|*main.py*|*uvicorn*main:app*)
pids="$pids $pid"
;;
esac
done < <(lsof -ti :"$PORT" 2>/dev/null || true)
pids="$(echo "$pids" | xargs)"
if [ -n "$pids" ]; then
echo "$pids" | xargs kill 2>/dev/null || true
sleep 0.5
echo "$pids" | xargs kill -9 2>/dev/null || true
echo "Stopped local PTS server on port $PORT"
return 0
fi
echo "Server not running"
}
server_status() {
read_port
if is_running; then
echo "Running PID $(cat "$PID_FILE") — http://localhost:$PORT"
exit 0
fi
echo "Not running"
exit 1
}
case "${1:-}" in
start) start_server ;;
stop) stop_server ;;
restart)
stop_server || true
sleep 0.5
start_server
;;
status) server_status ;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac