LibrePortal/scripts/network/ip/ip_find_available.sh
librelad c6dd2659be refactor(de-sudo): apps DB access via runInstallOp, not sudo
The apps SQLite DB ($docker_dir/$db_file) is owned by the manager user, so
read/write it AS the manager via runInstallOp instead of sudo (root). 48 call
sites across 28 scripts. In rooted this drops root->manager (correct owner);
in rootless it's the manager too (using runFileOp/dockerinstall here was the
'unable to open database' bug). The broken 'command -v sudo sqlite3' check
lines are left untouched (separate pre-existing issue).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Signed-off-by: librelad <librelad@digitalangels.vip>
2026-05-24 16:23:33 +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=$(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]}"
}