#!/bin/bash

dockerSwitcherSetSocketPermissions()
{
    # Check if rootless isnt needed
    if id "$CFG_DOCKER_INSTALL_USER" &>/dev/null; then
        local docker_install_user_id=$(id -u "$CFG_DOCKER_INSTALL_USER")
        local docker_rootless_socket="/run/user/${docker_install_user_id}/docker.sock"
        local docker_rootless_exist="true"
    else
        local docker_rootless_exist="false"
    fi

    isHeader "Docker Socket Checker"

    # The chmods run in the root-owned socket helper (runSocket), which computes
    # the socket paths itself and returns 3 when the socket is absent — so the
    # *_found flags (read downstream by stop_docker/swap_docker_type) come from
    # its exit code, no privileged `test -e` needed.
    if [[ $CFG_DOCKER_INSTALL_TYPE == "rooted" ]]; then
        if [[ $docker_rootless_exist == "false" ]]; then
            if runSocket rootless off; then
                checkSuccess "Removing read permissions from Rootless docker socket."
                docker_rootless_found="true"
            else
                docker_rootless_found="false"
            fi
        fi

        if runSocket rooted on; then
            checkSuccess "Adding read permissions to Rooted docker socket."
            docker_rooted_found="true"
        else
            isNotice "Rooted socket not found, installation needed..."
            docker_rooted_found="false"
        fi
    fi

    if [[ $CFG_DOCKER_INSTALL_TYPE == "rootless" ]]; then
        if runSocket rooted off; then
            checkSuccess "Removing read permissions from Rooted docker socket."
            docker_rooted_found="true"
        else
            docker_rooted_found="false"
        fi

        if runSocket rootless on; then
            checkSuccess "Adding read permissions to Rootless docker socket."
            docker_rootless_found="true"
        else
            isNotice "Rootless socket not found, installation needed..."
            docker_rootless_found="false"
        fi
    fi
}
