#!/bin/bash
# Healthcheck script for Passenger + Next.js app
# Logs status, restarts if needed, and sends email alerts

URL="https://newweb.sirentuomala.fi/"
APPDIR="/home/ehtalous/nodeapps/sirentuomala"
LOG="$APPDIR/monitor.log"
DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Check homepage (10s timeout). If curl fails, echo 000.
STATUS=$(/usr/bin/curl -fsS -m 10 -o /dev/null -w "%{http_code}" "$URL" 2>/dev/null || echo "000")

# Consider 2xx–4xx as "app answering". 5xx/000 means bad.
if [[ "$STATUS" -ge 200 && "$STATUS" -lt 500 ]]; then
  echo "[$DATE] OK $STATUS" >> "$LOG"
  exit 0
fi

# Log failure
echo "[$DATE] FAIL $STATUS — restarting Passenger app" >> "$LOG"

# Restart Passenger app by touching restart.txt
mkdir -p "$APPDIR/tmp"
touch "$APPDIR/tmp/restart.txt"

# Send email alert via PHP mail()
php -r "mail('claudio@sirentuomala.fi', '🚨 Sirentuomala app restart', 'The app was restarted at $DATE with 
status code $STATUS.', 'From: monitor@sirentuomala.fi');"

# Nudge the app after restart (warm it up)
sleep 2
/usr/bin/curl -fsS -m 10 "$URL" > /dev/null 2>&1 || true

exit 1

