#!/bin/bash

# URL to send the curl request to
URL="https://uca.fr"

# Number of times to execute the curl command
COUNT=${1:-10}

# Timeout for each request in seconds
TIMEOUT=5

# Time interval between requests in seconds
INTERVAL=2

# Generate ISO8601 timestamp for the log file name
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Log file location with ISO8601 timestamp
LOG_FILE="curl_requests_$TIMESTAMP.log"

# Initialize variables for stats
total_time=0
max_time=0
min_time=999999
success_count=0
failure_count=0

# Function to log both to console and file
log() {
    echo "$1" | tee -a $LOG_FILE
}

for (( i=1; i<=COUNT; i++ ))
do
    # Capture the response time and handle timeouts or failures
    response=$(curl -o /dev/null -s -S -w "%{time_total}" --max-time $TIMEOUT $URL)
    exit_code=$?
    
    if [ $exit_code -eq 0 ]; then
        # Successful request
        success_count=$((success_count + 1))
        response_time=$(echo "$response" | tr -d '\n')
        
        # Add to total time for average calculation
        total_time=$(echo "$total_time + $response_time" | bc)
        
        # Check if the response time is the maximum so far
        if (( $(echo "$response_time > $max_time" | bc -l) )); then
            max_time=$response_time
        fi
        
        # Check if the response time is the minimum so far
        if (( $(echo "$response_time < $min_time" | bc -l) )); then
            min_time=$response_time
        fi
        
        log "Request $i: Success - $response_time seconds"
    else
        # Failed request
        failure_count=$((failure_count + 1))
        log "Request $i: Failure (exit code: $exit_code)"
    fi

    # Wait for the defined interval before the next request
    sleep $INTERVAL
done

# Calculate the average response time if there were successful requests
if [ $success_count -gt 0 ]; then
    average_time=$(echo "scale=4; $total_time / $success_count" | bc)
else
    average_time=0
fi

# Calculate the failure percentage
failure_percentage=$(echo "scale=2; ($failure_count / $COUNT) * 100" | bc)

# Output the statistics
log "----------------------------------"
log "Number of requests: $COUNT, "
log "Successful requests: $success_count"
log "Failed requests: $failure_count"
log "Failure percentage: $failure_percentage%"
log "Average response time: $average_time seconds"
log "Maximum response time: $max_time seconds"
log "Minimum response time: $min_time seconds"
