#!/usr/bin/env bash

# User-owned WhatsApp gateway watchdog for cPanel/CloudLinux.
# The gateway stays on loopback; Laravel reaches it using port 39876.

set -u

HOME_ROOT="${HOME:-/home2/newsales}"
APP_ROOT="${HOME_ROOT}/public_html/saas.saleszawy.com/whatsapp-gateway"
NODE_BIN="${HOME_ROOT}/nodevenv/public_html/saas.saleszawy.com/whatsapp-gateway/22/bin/node"
RUNTIME_ROOT="${HOME_ROOT}/tmp/whatsapp-gateway-runtime"
PID_FILE="${RUNTIME_ROOT}/gateway.pid"
LOG_FILE="${RUNTIME_ROOT}/gateway.log"
LOCK_FILE="${RUNTIME_ROOT}/launcher.lock"
GATEWAY_PORT="${WHATSAPP_GATEWAY_PORT:-39876}"

mkdir -p "${RUNTIME_ROOT}"

(
  flock -n 9 || exit 0

  gateway_pid=""
  if [ -f "${PID_FILE}" ]; then
    gateway_pid="$(tr -cd '0-9' < "${PID_FILE}" 2>/dev/null || true)"
  fi

  is_gateway_running() {
    [ -n "$1" ] || return 1
    kill -0 "$1" 2>/dev/null || return 1
    [ -r "/proc/$1/cmdline" ] || return 1
    tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null | grep -Fq "${APP_ROOT}/index.js"
  }

  is_gateway_healthy() {
    command -v curl >/dev/null 2>&1 || return 0
    # Saving a bounded store can briefly occupy the Node event loop on a busy
    # shared host. Give a healthy process a little time before restarting it.
    curl -fsS --max-time 5 "http://127.0.0.1:${GATEWAY_PORT}/health/live" >/dev/null 2>&1
  }

  if is_gateway_running "${gateway_pid}"; then
    if is_gateway_healthy; then
      exit 0
    fi
    echo "[$(date -Is)] Gateway process is alive but health check failed; restarting it." >> "${LOG_FILE}"
    kill -TERM "${gateway_pid}" 2>/dev/null || true
    for _ in $(seq 1 20); do
      if ! is_gateway_running "${gateway_pid}"; then
        gateway_pid=""
        break
      fi
      sleep 0.25
    done
    if [ -n "${gateway_pid}" ] && is_gateway_running "${gateway_pid}"; then
      echo "[$(date -Is)] Gateway did not stop cleanly; refusing to start a second instance." >> "${LOG_FILE}"
      exit 1
    fi
  else
    # Never signal a stale PID file unless it still belongs to our gateway.
    gateway_pid=""
  fi

  cd "${APP_ROOT}" || exit 1
  if [ ! -x "${NODE_BIN}" ]; then
    echo "[$(date -Is)] Node runtime not found: ${NODE_BIN}" >> "${LOG_FILE}"
    exit 1
  fi
  if [ ! -d node_modules/express ]; then
    echo "[$(date -Is)] Missing Node dependencies. Run npm ci --omit=dev." >> "${LOG_FILE}"
    exit 1
  fi

  export HOME="${HOME_ROOT}"
  export NODE_ENV="production"
  export PORT="${GATEWAY_PORT}"
  export WHATSAPP_GATEWAY_HOST="127.0.0.1"

  nohup "${NODE_BIN}" index.js >> "${LOG_FILE}" 2>&1 < /dev/null &
  echo "$!" > "${PID_FILE}"
) 9>"${LOCK_FILE}"
