#!/bin/sh
# FarmHouse Core API health check. Run it over SSH from the api/ folder (or anywhere):
#   sh doctor.sh                                   all checks
#   sh doctor.sh --url=https://api.example.com     also check the API from outside, with CORS
#   sh doctor.sh --start                           also start a copy of the API and report start-up errors
#   sh doctor.sh --json > report.json              machine-readable
# Secrets are never printed. Exit code 0 when nothing failed.
cd "$(dirname "$0")" || exit 1

# cPanel "Setup Node.js App" keeps node in a per-app virtual environment: ~/nodevenv/<app folder>/<version>/.
# Use this app's newest one; then any other; then whatever node is on PATH.
if [ -d "$HOME/nodevenv" ]; then
  rel=${PWD#"$HOME"/}
  act=$(ls -d "$HOME/nodevenv/$rel"/*/bin/activate 2>/dev/null | sort -V | tail -n 1)
  [ -z "$act" ] && act=$(ls -d "$HOME"/nodevenv/*/*/bin/activate "$HOME"/nodevenv/*/*/*/bin/activate 2>/dev/null | sort -V | tail -n 1)
  # shellcheck disable=SC1090
  [ -n "$act" ] && . "$act"
fi
if ! command -v node >/dev/null 2>&1; then
  echo "node is not on PATH. In cPanel open Setup Node.js App, create the app (Node.js 22+), and run the"
  echo "'source .../bin/activate' command it shows, then run this again."
  exit 1
fi
exec node dist/doctor.mjs "$@"
