#!/bin/bash

# Resolves the system user that owns the Docker install — and therefore the
# backup repos and container files. Rooted installs run as $sudo_user_name;
# rootless installs use $CFG_DOCKER_INSTALL_USER. Falls back to $sudo_user_name
# and finally 'libreportal' so the value is never empty: an empty user turns
# `sudo -u "$docker_install_user"` into a sudo usage error. Reads only config,
# so it is safe to call from any CLI entry point.
resolveDockerInstallUser()
{
	if [[ "$CFG_DOCKER_INSTALL_TYPE" == "rootless" ]]; then
		docker_install_user="$CFG_DOCKER_INSTALL_USER"
	else
		docker_install_user="$sudo_user_name"
	fi
	[[ -z "$docker_install_user" ]] && docker_install_user="${sudo_user_name:-libreportal}"
}

checkInstallTypeRequirement()
{
	if [[ "$OS_TYPE" == "Ubuntu" || "$OS_TYPE" == "Debian" ]]; then
		ISCOMP=$( (docker compose -v ) 2>&1 )
		ISUFW=$( (runSystem ufw status ) 2>&1 )
		ISUFWD=$( (runSystem ufw-docker) 2>&1 )

		resolveDockerInstallUser

		if [[ $CFG_DOCKER_INSTALL_TYPE == "rooted" ]]; then
			# Used for checking if rooted docket is active
			ISACT=$( (runSystem systemctl is-active docker ) 2>&1 )
		elif [[ $CFG_DOCKER_INSTALL_TYPE == "rootless" ]]; then
			# Used for checking the rootless user
			local ISUSER=$( (id -u "$CFG_DOCKER_INSTALL_USER") 2>&1 )
			if [[ "$ISUSER" == *"no such user"* ]]; then
				ISACT=$(command -v docker &> /dev/null)
			fi
		fi
	fi
}