#!/bin/bash
# fast_benchmark.sh (Online version)

IP=$(hostname -I | awk '{print $1}')
MASSCAN="./masscan_portable"

chmod +x $MASSCAN

# Run a real internet scan for 10 seconds to find actual PPS
# We use a high rate but limited time to see where the network/CPU caps out
OUT=$(timeout 12 $MASSCAN 0.0.0.0/0 -p80 --rate 1000000 --exclude 255.255.255.255 2>&1)

# Masscan output uses \r for the status line. We replace it with \n to parse.
LAST_LINE=$(echo "$OUT" | tr '\r' '\n' | grep "rate:" | tail -n 1)

# Extract raw value
RAW_RATE=$(echo "$LAST_LINE" | grep -oP 'rate:\s*\K[0-9.]+')

# Determine if it's kpps or pps
PPS="0"
if [[ "$LAST_LINE" == *"kpps"* ]]; then
    # Convert kpps (e.g. 12.34) to raw pps
    PPS=$(awk -v r="$RAW_RATE" 'BEGIN {print (r * 1000)}')
else
    PPS=$RAW_RATE
fi

# Fallback to 0 if empty
if [ -z "$PPS" ]; then PPS="0"; fi

echo "{\"ip\": \"$IP\", \"status\": \"success\", \"actual_pps\": \"$PPS\", \"cpu\": \"$(grep 'model name' /proc/cpuinfo | head -n 1 | cut -d: -f2 | xargs)\"}"
