#!/bin/bash
# Flask App Monitoring Script
# This script checks if the Jadwa AI Flask app is running and restarts it if needed

APP_DIR="/home/ashraffarid2010/jadwaai.com"
APP_PORT=5006
APP_USER="pakchoi"
LOG_FILE="$APP_DIR/logs/monitor.log"

# Create logs directory if it doesn't exist
mkdir -p "$APP_DIR/logs"

# Function to log messages
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# Check if app is responding
check_app() {
    curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:$APP_PORT/ --max-time 10
}

# Check if gunicorn process is running
check_process() {
    pgrep -f "gunicorn.*$APP_PORT" > /dev/null
    echo $?
}

log_message "=== Starting Flask app monitoring check ==="

# First check if process is running
if [ $(check_process) -eq 0 ]; then
    log_message "✓ Gunicorn process is running on port $APP_PORT"

    # Check if app is responding
    HTTP_CODE=$(check_app)
    if [ "$HTTP_CODE" = "200" ]; then
        log_message "✓ App is responding correctly (HTTP $HTTP_CODE)"
        exit 0
    else
        log_message "✗ App is not responding (HTTP $HTTP_CODE)"
        log_message "Attempting to restart..."
    fi
else
    log_message "✗ Gunicorn process is NOT running on port $APP_PORT"
    log_message "Attempting to start..."
fi

# Try to stop any existing process first
pkill -f "gunicorn.*$APP_PORT" 2>/dev/null
sleep 2

# Start the app
cd "$APP_DIR" || exit 1
export FLASK_ENV=production
source venv/bin/activate

# Start gunicorn with proper configuration
nohup venv/bin/gunicorn -w 4 -b 127.0.0.1:$APP_PORT --timeout 120 --keep-alive 5 --max-requests 1000 --max-requests-jitter 50 run:app >> "$APP_DIR/logs/gunicorn.log" 2>&1 &

# Wait for app to start
sleep 5

# Verify it started
if [ $(check_process) -eq 0 ]; then
    HTTP_CODE=$(check_app)
    if [ "$HTTP_CODE" = "200" ]; then
        log_message "✓ Successfully started Flask app (HTTP $HTTP_CODE)"
    else
        log_message "⚠ Flask app started but not responding correctly (HTTP $HTTP_CODE)"
    fi
else
    log_message "✗ Failed to start Flask app"
    # Send alert (you can add email/notification here)
fi

log_message "=== Monitoring check complete ==="
