#!/bin/bash
# Diagnose 503 on chart.tradingbite.net — run as dulcfokx
set -eu

APP_ROOT="${HOME}/chart.tradingbite.net"
PORT="${PORT:-3010}"
cd "$APP_ROOT"

export NVM_DIR="${HOME}/.nvm"
# shellcheck source=/dev/null
[ -s "${NVM_DIR}/nvm.sh" ] && . "${NVM_DIR}/nvm.sh"
nvm use 22 2>/dev/null || true

echo "=== 1) Is Node app listening on ${PORT}? ==="
if curl -sI "http://127.0.0.1:${PORT}/" | head -3; then
  echo "(If you see HTTP/1.1 200 above, Node is OK — problem is Apache/proxy.)"
else
  echo "Node NOT responding. Restarting PM2..."
  bash deploy/chart-server-start.sh
  sleep 2
  curl -sI "http://127.0.0.1:${PORT}/" | head -3 || true
fi

echo ""
echo "=== 2) PM2 ==="
pm2 status 2>/dev/null || echo "pm2 not running"

echo ""
echo "=== 3) .htaccess (last 25 lines) ==="
tail -25 .htaccess 2>/dev/null || echo "no .htaccess"

echo ""
echo "=== 4) Remove broken proxy lines (fixes many 503s) ==="
if [ -f .htaccess ] && grep -q "127.0.0.1:${PORT}" .htaccess; then
  cp .htaccess ".htaccess.before-fix-$(date +%s)"
  grep -v "127.0.0.1:${PORT}" .htaccess | grep -v "htaccess-proxy" | sed '/^RewriteEngine On$/d' | sed '/^RewriteCond %{REQUEST_FILENAME}/d' | sed '/^RewriteRule \^(.*)\$/d' > .htaccess.tmp || true
  # Safer: restore cPanel-only file if backup exists
  if [ -f .htaccess.bak ]; then
    cp .htaccess.bak .htaccess
    echo "Restored .htaccess from .htaccess.bak"
  else
    echo "No .htaccess.bak — edit manually or use cPanel Node.js App (see deploy/cpanel-node.txt)"
  fi
fi

echo ""
echo "=== NEXT: use cPanel 'Setup Node.js App' for chart.tradingbite.net ==="
cat deploy/cpanel-node.txt
