#!/usr/bin/env bash # Deploy backend: build release, stop running process gracefully (PID file & pgrep fallback), rotate logs, and start via nohup # Usage: # ENV_FILE=prod ./scripts/deploy_backend.sh # ENV_FILE=staging ./scripts/deploy_backend.sh # Notes: # - ENV_FILE will be exported for the backend to decide which .env to load (e.g., .env.prod). # - PID is stored in backend/udmin.pid. set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. && pwd)" BACKEND_DIR="$ROOT_DIR/backend" BIN_PATH="$BACKEND_DIR/target/release/udmin" LOG_FILE="$BACKEND_DIR/udmin.log" PID_FILE="$BACKEND_DIR/udmin.pid" ENV_FILE_VALUE="${ENV_FILE:-prod}" cd "$BACKEND_DIR" echo "[backend] Building release binary..." cargo build --release if [ ! -x "$BIN_PATH" ]; then echo "[backend] ERROR: Binary not found or not executable: $BIN_PATH" >&2 exit 1 fi # Gracefully stop existing process (PID file first) stop_pid() { local pid="$1" if [ -z "$pid" ]; then return 0; fi if ! ps -p "$pid" >/dev/null 2>&1; then return 0; fi echo "[backend] Stopping udmin (pid=$pid) ..." kill -TERM "$pid" || true for i in {1..10}; do if ps -p "$pid" >/dev/null 2>&1; then sleep 1 else break fi done if ps -p "$pid" >/dev/null 2>&1; then echo "[backend] Force killing udmin (pid=$pid) ..." kill -KILL "$pid" || true fi } # 1) Stop by PID file if present if [ -f "$PID_FILE" ]; then PID_CONTENT="$(cat "$PID_FILE" 2>/dev/null || true)" if [ -n "$PID_CONTENT" ]; then stop_pid "$PID_CONTENT" fi rm -f "$PID_FILE" fi # 2) Fallback: stop any process matching the release binary path (safe, avoids killing debug run) PGREP_PIDS="$(pgrep -f "$BIN_PATH" 2>/dev/null || true)" if [ -n "$PGREP_PIDS" ]; then echo "[backend] Found existing udmin by path, stopping: $PGREP_PIDS" for p in $PGREP_PIDS; do stop_pid "$p" done fi # Rotate log TS="$(date +%Y%m%d%H%M%S)" if [ -f "$LOG_FILE" ]; then mv "$LOG_FILE" "$LOG_FILE.$TS" || true fi echo "[backend] Starting udmin (ENV_FILE=$ENV_FILE_VALUE) ..." export ENV_FILE="$ENV_FILE_VALUE" nohup "$BIN_PATH" > "$LOG_FILE" 2>&1 & NEW_PID=$! echo "$NEW_PID" > "$PID_FILE" echo "[backend] Started. PID=$NEW_PID" echo "[backend] Logs: $LOG_FILE" echo "[backend] PID file: $PID_FILE"