#!/bin/bash

set -euo pipefail

# Script to test maximum string length across OLD Node versions (7 and earlier)
# Using Docker to avoid cross-architecture issues

# Function to test a Node version using Docker
test_node_version() {
    local version="$1"
    
    echo "Testing Node ${version}..." >&2
    
    # Try to run the test with Docker
    # Use --platform linux/amd64 for older Node versions that don't have ARM builds
    docker run --platform linux/amd64 --rm "node:${version}" \
        node --max-old-space-size=4096 -e '
        var low=0,high=4*1024*1024*1024,maxLen=0;
        while(low<=high){
            var mid=Math.floor((low+high)/2);
            try{
                var s=new Array(mid+1).join("x");
                maxLen=mid;
                low=mid+1
            }catch(e){
                high=mid-1
            }
        }
        console.log(JSON.stringify({
            maxLength:maxLen,
            v8:process.versions.v8,
            node:process.versions.node
        }))
    ' 2>/dev/null || {
        echo "Failed to test ${version}" >&2
        return 1
    }
}

# Generate list of versions to test
echo "["
first=true

# Test versions from 7 down to 0
for major in {7..0}; do
    echo "Checking for Node v${major}..." >&2
    
    # Check if Docker image exists for this version
    # Try a few common tags
    for tag in "${major}" "${major}.0" "${major}.0.0"; do
        if docker manifest inspect "node:${tag}" > /dev/null 2>&1; then
            echo "Found Node v${major} with tag ${tag}" >&2
            
            if result=$(test_node_version "${tag}"); then
                if [ "$first" = true ]; then
                    first=false
                else
                    echo ","
                fi
                echo "$result"
            fi
            break
        fi
    done
done

echo ""
echo "]"
