#!/bin/bash
echo "start"
# Get the directory where the script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
HEY_BINARY="$SCRIPT_DIR/hey_linux_amd64"

echo "=========================================="
echo "Distributed Stock Provider - Load Test"
echo "=========================================="
echo ""

# Check if local hey binary exists
if [ ! -f "$HEY_BINARY" ]; then
    echo "Error: hey binary not found at $HEY_BINARY"
    echo "Please ensure hey_linux_amd64 is in the load-test directory"
    exit 1
fi

# Make sure the binary is executable
chmod +x "$HEY_BINARY"

echo "Starting MAXIMUM LOAD test with Hey..."
echo ""
echo "Test Configuration:"
echo "  - 50 concurrent workers"
echo "  - 5,000 total requests"
echo "  - HTTP/2 disabled for better performance"
echo "  - Keep-alive connections enabled"
echo "  - Target: http://localhost:80/api/stocks/cached/all"
echo ""
echo "WARNING: This will generate MASSIVE load on your system!"
echo ""

# First, get an auth token
echo "Getting authentication token..."
AUTH_RESPONSE=$(curl -s -X POST http://localhost:80/api/auth/register \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"loadtest_$(date +%s)\",\"password\":\"testpass123\"}")

TOKEN=$(echo $AUTH_RESPONSE | grep -o '"accessToken":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "Failed to get auth token. Trying with existing user..."
    AUTH_RESPONSE=$(curl -s -X POST http://localhost:80/api/auth/login \
      -H "Content-Type: application/json" \
      -d "{\"username\":\"testuser\",\"password\":\"testpass123\"}")
    
    TOKEN=$(echo $AUTH_RESPONSE | grep -o '"accessToken":"[^"]*' | cut -d'"' -f4)
fi

if [ -z "$TOKEN" ]; then
    echo "ERROR: Could not obtain authentication token"
    exit 1
fi

echo "Token obtained successfully!"
echo ""
echo "Running load test..."
echo ""

# Run the load test with hey
# -n: Total number of requests (5,000)
# -c: Number of concurrent workers (500)
# -disable-keepalive: Disabled (we want keep-alive for better performance)
# -disable-compression: Disabled (we want compression)
# -h2: Disabled (HTTP/1.1 is often faster for simple requests)
"$HEY_BINARY" -n 5000 -c 50 -H "Authorization: Bearer $TOKEN" http://localhost:80/api/stocks/cached/all

echo ""
echo "=========================================="
echo "Load test completed!"
echo "=========================================="
echo ""
echo "Check the summary above for:"
echo "  - Total requests and requests/sec"
echo "  - Response time distribution"
echo "  - Status code distribution"
echo "  - Load balancing across backend instances"
echo "=========================================="

# Made with Bob
