#!/bin/bash
# Canonical, idempotent restart for the zucegroup Node.js app. Always use
# this instead of a bare `cloudlinux-selector restart` - that command has
# repeatedly failed to actually kill the previous worker on this account
# (see docs/DEPLOYMENT.md), leaving stale lsnode: processes to accumulate
# across deploys. Truehost support found four of them stacked up on
# 2026-10-21, which is exactly the failure mode this script exists to rule
# out: it kills every matching worker by exact PID, confirms none remain,
# only then starts fresh, and verifies the result before exiting.
#
# Deliberately avoids `mapfile < <(...)` / process substitution - that
# relies on /dev/fd, which isn't reliably available when this runs as a
# non-interactive `ssh host 'bash script.sh'` command (confirmed by testing
# on this account: it silently failed, leaving every array empty and every
# check falsely reporting "clean" regardless of actual state). Plain
# command substitution + word-splitting on PIDs (always plain numbers, so
# safe to split on whitespace) works reliably here instead.
#
# Usage (on the server, inside ~/app.zucegroup.com):
#   bash deploy/safe-restart.sh
#
# Exits non-zero if it can't get to a single clean worker, so it's safe to
# chain after a deploy (e.g. `git pull && bash deploy/safe-restart.sh`)
# without silently leaving things in a bad state.

APP_DOMAIN="app.zucegroup.com"
APP_ROOT="/home/wemqjdto/app.zucegroup.com"
PUBLIC_URL="https://zucegroup.com/login"
MATCH_PATTERN="lsnode:.*app\.zucegroup\.com"

find_worker_pids() {
  ps -u "$(whoami)" -o pid,cmd --no-headers | grep -E "$MATCH_PATTERN" | awk '{print $1}'
}

echo "== Step 1: finding existing workers =="
PIDS="$(find_worker_pids)"
PID_COUNT=$(echo -n "$PIDS" | grep -c . 2>/dev/null)
if [ -z "$PIDS" ]; then
  echo "No existing workers found."
else
  echo "Found $PID_COUNT worker(s):"
  echo "$PIDS"
  echo "== Step 2: killing them by exact PID =="
  for pid in $PIDS; do
    kill -9 "$pid" 2>/dev/null && echo "Killed $pid" || echo "Could not kill $pid (already gone?)"
  done
  sleep 2
fi

echo "== Step 3: confirming none remain =="
REMAINING="$(find_worker_pids)"
if [ -n "$REMAINING" ]; then
  echo "FAIL: worker(s) survived the kill:"
  echo "$REMAINING"
  echo "Not proceeding to start - investigate manually before retrying."
  exit 1
fi
echo "Confirmed clean."

echo "== Step 4: starting fresh =="
cloudlinux-selector restart --json --interpreter nodejs --domain "$APP_DOMAIN" --app-root "$APP_ROOT"

echo "== Step 5: triggering a lazy spawn and checking HTTP health =="
HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$PUBLIC_URL")
echo "HTTP $HTTP_CODE from $PUBLIC_URL"

echo "== Step 6: verifying exactly one fresh worker =="
FINAL="$(find_worker_pids)"
FINAL_COUNT=0
if [ -n "$FINAL" ]; then
  FINAL_COUNT=$(echo "$FINAL" | wc -l)
fi
echo "Worker(s) now running: $FINAL_COUNT"
echo "$FINAL"

if [ "$FINAL_COUNT" -ne 1 ]; then
  echo "FAIL: expected exactly 1 worker, found $FINAL_COUNT."
  exit 1
fi
if [ "$HTTP_CODE" != "200" ]; then
  echo "FAIL: app did not return HTTP 200."
  exit 1
fi

echo "OK: single clean worker, site responding."
