#!/bin/bash

# Find available IP in pool with randomization
ipFindAvailable()
{
    # Extract subnet base from CFG_NETWORK_SUBNET and use hardcoded sensible defaults
    local subnet_base=$(echo "$CFG_NETWORK_SUBNET" | cut -d'/' -f1 | cut -d'.' -f1-3)
    local start_last=2      # Hardcoded sensible default: .2
    local end_last=254     # Hardcoded sensible default: .254
    
    local existing_ips=$(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT resource_value FROM network_resources WHERE resource_type = 'ip' AND status = 'active';" 2>/dev/null)
    if [[ $? -ne 0 ]]; then
        isError "Database query failed while checking existing IPs"
        available_ip=""
    fi
    
    # Create an array to store available IPs
    local available_ip_pool=()
    
    # Randomization: Shuffle the IP range
    local ip_range=($(seq $start_last $end_last | shuf))
    
    for i in "${ip_range[@]}"; do
        # Skip reserved IPs (1=gateway, 254=broadcast)
        if [[ $i -eq 1 || $i -eq 254 ]]; then
            continue
        fi
        
        local test_ip="${subnet_base}.${i}"
        
        # Check if IP is already allocated
        if [[ "$existing_ips" != *"$test_ip"* ]]; then
            available_ip_pool+=("$test_ip")
        fi
    done
    
    # Check if we have any available IPs
    if [[ ${#available_ip_pool[@]} -eq 0 ]]; then
        isError "No available IP addresses in subnet $CFG_NETWORK_SUBNET and all expansion ranges exhausted"
        available_ip=""
    fi
    
    # Randomly select an IP from the available pool
    local random_index=$((RANDOM % ${#available_ip_pool[@]}))
    available_ip="${available_ip_pool[$random_index]}"
}
