#!/bin/bash

# Memory measurement script for Wasot random file generation
# Added memory limit feature after discovering unbounded memory growth issue
# (see commit 0cf597f: fix bounded channel to resolve memory growth)
#
# Usage: ./measure_memory.sh [EVENT_COUNT] [MEMORY_LIMIT_GB]
# 
# Default parameters optimized for testing memory fix:
# - 400K events: Previously showed constant ~60MB usage (safe baseline)
# - 2GB limit: Prevents runaway memory from crashing system during testing
N=${1:-400000}
MEMORY_LIMIT_GB=${2:-2}

# Check if GNU time is available
if ! command -v /usr/bin/time &>/dev/null; then
  echo "Error: GNU time is required. Install with: sudo apt-get install time"
  exit 1
fi

# Check if ulimit is available for memory limiting
# Memory limiting prevents system crashes during large file tests
# Essential for testing fix that reduced memory from 3.4GB → 60MB for 100M events
if ! command -v ulimit &>/dev/null; then
  echo "Warning: ulimit not available, cannot set memory limit"
  MEMORY_LIMIT_GB=0
fi

echo "Measuring memory usage for wasot random with N=$N lines..."
if [ "$MEMORY_LIMIT_GB" -gt 0 ]; then
  echo "Memory limit set to ${MEMORY_LIMIT_GB}GB"
  # Convert GB to KB for ulimit (virtual memory limit)
  # This catches runaway memory before it impacts system stability
  MEMORY_LIMIT_KB=$((MEMORY_LIMIT_GB * 1024 * 1024))
else
  echo "No memory limit set"
fi

# Run the command with GNU time to measure peak memory usage
# %M gives maximum resident set size in KB (actual RAM used)
# 
# Two execution paths handle memory limiting:
# 1. With limit: ulimit constrains virtual memory to catch runaway growth
# 2. Without limit: Direct execution for baseline measurements
if [ "$MEMORY_LIMIT_GB" -gt 0 ]; then
  # Run with memory limit using subshell to isolate ulimit scope
  # If process exceeds limit, it gets killed, preventing system impact
  (ulimit -v $MEMORY_LIMIT_KB; /usr/bin/time -f "Peak memory: %M KB" \
    cargo run --release --bin wasot -- random -n "$N" 2>&1 >/dev/null) |
    awk '/Peak memory:/ {printf "%.2f MB\n", $3/1024}'
else
  # Run without memory limit for unrestricted measurements
  /usr/bin/time -f "Peak memory: %M KB" \
    cargo run --release --bin wasot -- random -n "$N" 2>&1 >/dev/null |
    awk '/Peak memory:/ {printf "%.2f MB\n", $3/1024}'
fi

