#!/usr/bin/env bash
# ============================================================================
# HostTiller — Inertia SSR keep-alive launcher
#
# Purpose:
#   HostTiller is an Inertia.js (React) app. Without server-side rendering the
#   homepage <body> ships empty, so search-engine crawlers (which do not run
#   JavaScript) report 0 words / no paragraphs. This script makes sure the
#   Inertia SSR node server (bootstrap/ssr/ssr.js) is always running on
#   127.0.0.1:13714, which is what config/inertia.php expects.
#
# Usage (pick ONE):
#   1) cPanel "Setup Node.js App" (Application Manager / Passenger):
#        App root   : <project dir>
#        Startup    : /usr/bin/env node bootstrap/ssr/ssr.js
#        (passenger keeps it alive automatically — the recommended option)
#
#   2) Cron keep-alive — add this line every minute:
#        * * * * * /bin/bash /home/USER/hosttiller.com/start-ssr.sh >/dev/null 2>&1
#
#   3) Run manually (SSH):  bash start-ssr.sh
# ============================================================================

APP_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG="$APP_DIR/storage/logs/ssr.log"
PID_FILE="$APP_DIR/storage/logs/ssr.pid"
URL="http://127.0.0.1:13714"
PORT=13714

mkdir -p "$APP_DIR/storage/logs"

# 1) Already up? (pid file + pid alive + port actually responding)
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE" 2>/dev/null)
    if [ -n "$OLD_PID" ] && kill -0 "$OLD_PID" 2>/dev/null && \
       curl -s -o /dev/null --max-time 2 "$URL"; then
        exit 0
    fi
fi

# 2) Running but pid file stale/missing?
if command -v pgrep >/dev/null 2>&1; then
    if pgrep -f "bootstrap/ssr/ssr.js" >/dev/null 2>&1 && \
       curl -s -o /dev/null --max-time 2 "$URL"; then
        exit 0
    fi
fi

# Kill any orphaned instance on our port owned by this user before restarting.
if command -v fuser >/dev/null 2>&1; then
    fuser -k "$PORT/tcp" >/dev/null 2>&1
fi

cd "$APP_DIR" || exit 1
nohup node bootstrap/ssr/ssr.js >> "$LOG" 2>&1 &
NEW_PID=$!
echo "$NEW_PID" > "$PID_FILE"
echo "$(date '+%Y-%m-%d %H:%M:%S') — SSR started (pid $NEW_PID)" >> "$LOG"