LibrePortal/scripts/network/ip/ip_find_available.sh
librelad 875a60f90f LibrePortal v0.1.0 — initial release
A free, open, self-hosted app platform (GNU AGPLv3): one-click app deploys,
Traefik reverse proxy with automatic SSL, rootless Docker support, gluetun
VPN routing, and a web dashboard to manage it all.

Free & open forever to self-host; optional paid hosted services fund it.
See PROMISE.md.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

Signed-off-by: librelad <librelad@digitalangels.vip>
2026-05-21 20:37:54 +01:00

47 lines
1.6 KiB
Bash
Executable File

#!/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=$(sudo 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]}"
}