#!/usr/bin/env bash
set -euo pipefail

APP="fastapi-app"        
ECOS="/home/juncfhox/public_html/juncera_api/ecosystem.config.js"      
HEALTH_URL="https://api.junceraautomations.com/"   

# Ensure PM2 is up on boot (no-op if already set)
if ! pm2 ping >/dev/null 2>&1; then
  eval "$(pm2 startup --silent | tail -n 1)" || true
fi

# Start app if missing
if ! pm2 describe "$APP" >/dev/null 2>&1; then
  pm2 start "$ECOS" --only "$APP"
  pm2 save
fi

# If app not online, bring it back
if ! pm2 status "$APP" | grep -q "online"; then
  pm2 restart "$APP" || pm2 start "$ECOS" --only "$APP"
  pm2 save
fi

# Health probe; restart if unhealthy
if ! curl -fsS --max-time 6 "$HEALTH_URL" >/dev/null; then
  pm2 restart "$APP"
  pm2 save
fi
