#!/bin/bash

# CFG↔docker subnet adoption: if the docker network already exists with a
# different /24 than CFG, treat docker's value as the truth and update CFG.
# Apps' allocated IPs are still inside docker's subnet, so nothing else needs
# re-IPing. (A genuine user-initiated subnet change is a `libreportal app
# install <name> --reset-network` per app — fresh compose + fresh IPs from
# the new subnet via the standard idempotent install path.)
adoptDockerSubnet()
{
	local current_subnet="$1"
	[[ -z "$current_subnet" ]] && return 0
	updateConfigOption "CFG_NETWORK_SUBNET" "$current_subnet"
	CFG_NETWORK_SUBNET="$current_subnet"
	isSuccessful "Adopted docker's subnet into CFG: $current_subnet"
}

checkDockerNetworkRequirement()
{
	if [[ $CFG_REQUIREMENT_DOCKER_NETWORK == "true" ]]; then
		if [[ $CFG_DOCKER_INSTALL_TYPE == "rootless" ]]; then
			if dockerCommandRun "docker network inspect $CFG_NETWORK_NAME > /dev/null 2>&1"; then
				local current_subnet=$(dockerCommandRun "docker network inspect $CFG_NETWORK_NAME --format '{{range .IPAM.Config}}{{.Subnet}}{{end}}' 2>/dev/null")

				if [[ "$current_subnet" == "$CFG_NETWORK_SUBNET" ]]; then
					isSuccessful "Docker Network $CFG_NETWORK_NAME exists with matching subnet"
				else
					adoptDockerSubnet "$current_subnet"
				fi
			else
				isNotice "Docker Network $CFG_NETWORK_NAME not found."
				DOCKER_NETWORK_SETUP_NEEDED="true"
				((preinstallneeded++))
			fi
		elif [[ $CFG_DOCKER_INSTALL_TYPE == "rooted" ]]; then
			if runFileOp docker network inspect $CFG_NETWORK_NAME > /dev/null 2>&1; then
				local current_subnet=$(runFileOp docker network inspect $CFG_NETWORK_NAME --format '{{range .IPAM.Config}}{{.Subnet}}{{end}}' 2>/dev/null)

				if [[ "$current_subnet" == "$CFG_NETWORK_SUBNET" ]]; then
					isSuccessful "Docker Network $CFG_NETWORK_NAME exists with matching subnet"
				else
					adoptDockerSubnet "$current_subnet"
				fi
			else
				isNotice "Docker Network $CFG_NETWORK_NAME not found."
				DOCKER_NETWORK_SETUP_NEEDED="true"
				((preinstallneeded++))
			fi
		fi
	fi
}
