#!/bin/bash

# URL of the application's health endpoint
URL="https://gheyma-app-2b88268529f9.hosted.ghaymah.systems/health"

# Maximum time to wait for a response (seconds)
TIMEOUT=10

# Monitoring interval (seconds)
INTERVAL=30

# Log file
LOG_FILE="monitor.log"

# Continuously monitor the application
while true; do

    # Get HTTP status code and response time
    RESPONSE=$(curl -s \
        --max-time "$TIMEOUT" \
        -o /dev/null \
        -w "%{http_code} %{time_total}" \
        "$URL")

    # Check if curl was successful
    if [ $? -ne 0 ]; then

        # Server is unreachable or request timed out
        MESSAGE="$(date '+%Y-%m-%d %H:%M:%S') - UNREACHABLE - Connection failed or timed out"

    else

        # Extract HTTP status code
        STATUS=$(echo "$RESPONSE" | awk '{print $1}')

        # Extract response time
        RESPONSE_TIME=$(echo "$RESPONSE" | awk '{print $2}')

        # Check application health
        if [ "$STATUS" = "200" ]; then
            MESSAGE="$(date '+%Y-%m-%d %H:%M:%S') - HEALTHY - Status: $STATUS - Response time: ${RESPONSE_TIME}s"
        else
            MESSAGE="$(date '+%Y-%m-%d %H:%M:%S') - UNHEALTHY - Status: $STATUS - Response time: ${RESPONSE_TIME}s"
        fi
    fi

    # Print result to terminal
    echo "$MESSAGE"

    # Save result to log file
    echo "$MESSAGE" >> "$LOG_FILE"

    # Wait before the next health check
    sleep "$INTERVAL"

done