#!/bin/bash
# SmartScreens Monitoring Script
# Keeps the application running by checking PHP-FPM and nginx status

SITE_URL="https://m.smartscreens.online"
PHP_FPM_SERVICE="ea-php81-php-fpm"
LOG_FILE="/home/ashraffarid2010/m.smartscreens.online/monitor.log"

check_php_fpm() {
    if [ ! -S /tmp/php81.sock ]; then
        echo "[$(date)] PHP-FPM socket not found" >> "$LOG_FILE"
        return 1
    fi
    return 0
}

check_site() {
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$SITE_URL" 2>/dev/null)
    if [ "$HTTP_CODE" != "200" ]; then
        echo "[$(date)] Site returned HTTP $HTTP_CODE" >> "$LOG_FILE"
        return 1
    fi
    return 0
}

restart_services() {
    echo "[$(date)] Attempting to restart PHP-FPM..." >> "$LOG_FILE"
    /scripts/restartsrv_apache_php_fpm ea-php81 2>/dev/null || \
    /scripts/restartsrv_php_fpm ea-php81 2>/dev/null || \
    systemctl restart php-fpm 2>/dev/null
    sleep 3
}

# Main monitoring loop
if ! check_php_fpm || ! check_site; then
    restart_services
    if check_php_fpm && check_site; then
        echo "[$(date)] Services restarted successfully" >> "$LOG_FILE"
    else
        echo "[$(date)] FAILED: Could not restore services" >> "$LOG_FILE"
    fi
fi
