#!/bin/bash

updateDockerNetworkSubnet()
{
    if [[ "$CFG_NETWORK_SUBNET" == *"$default_subnet"* ]]; then
        # Generate random subnet, retrying if it ever collides with the
        # wireguard tunnel subnet. Belt and braces — wireguard uses the
        # 200-250 second-octet range and we use 100-149 here, so they
        # can't overlap by design, but the explicit check guards future
        # changes to either range.
        local new_subnet=""
        local _attempts=0
        while (( _attempts < 50 )); do
            local random_second=$(( RANDOM % 50 + 100 ))  # 100-149
            local random_third=$(( RANDOM % 256 ))        # 0-255
            new_subnet="10.${random_second}.${random_third}.0/24"
            if [[ -z "$CFG_WIREGUARD_SUBNET" ]] \
               || [[ "${new_subnet%/*}" != "${CFG_WIREGUARD_SUBNET}" ]]; then
                break
            fi
            ((_attempts++))
        done

        # Update configuration using our standard updater
        updateConfigOption "CFG_NETWORK_SUBNET" "$new_subnet"
        checkSuccess "Randomized network subnet to: $new_subnet"

        # Update the global variable for current session
        CFG_NETWORK_SUBNET="$new_subnet"
    else
        isNotice "Network subnet already customized: $CFG_NETWORK_SUBNET"
    fi
}
