#!/bin/bash

# Docker socket LibrePortal tag replacements based on installation type
# Now uses universal tag manager instead of sed operations
tagsProcessorSocketConfiguration()
{
    local full_file_path="$1"
    local CFG_DOCKER_INSTALL_TYPE="$2"
    local CFG_DOCKER_INSTALL_USER="$3"
    local docker_rooted_socket="$4"
    
    # Socket mount must be RW. Mounting the docker socket :ro doesn't
    # provide real security — anyone with read access to the socket can
    # send arbitrary commands; the daemon doesn't enforce ro at the
    # protocol layer. But it DOES prevent connect() in some kernel /
    # docker version combos, which silently breaks API clients (e.g.
    # the WebUI services tab over the HTTP API).
    local socket_path=""
    if [[ $CFG_DOCKER_INSTALL_TYPE == "rootless" ]]; then
        local docker_install_user_id=$(id -u "$CFG_DOCKER_INSTALL_USER")
        socket_path="/run/user/${docker_install_user_id}/docker.sock"
    elif [[ $CFG_DOCKER_INSTALL_TYPE == "rooted" ]]; then
        socket_path="$docker_rooted_socket"
    fi

    if [[ -n "$socket_path" ]]; then
        tagsManagerUpdateUniversalTag "$full_file_path" "SOCKET_TAG" "${socket_path}:${socket_path}"

        # Resolve the socket's group GID so the container can connect via
        # group_add.
        local socket_gid=""
        if [[ $CFG_DOCKER_INSTALL_TYPE == "rootless" ]]; then
            # Rootless: container runs as UID 0 = the install user = socket
            # owner, so inside the userns the socket's group is root (0). The
            # host shows a high sub-GID (e.g. 166528); using that would make
            # group_add call setgroups() with a GID outside the userns → EINVAL
            # and the container fails to start.
            socket_gid=0
        else
            # Rooted: socket is owned root:docker mode 660, so a non-member UID
            # needs the docker group via group_add or it sees EACCES.
            if [[ -S "$socket_path" ]]; then
                socket_gid=$(stat -c '%g' "$socket_path" 2>/dev/null)
            fi
            [[ -z "$socket_gid" ]] && socket_gid=$(getent group docker 2>/dev/null | cut -d: -f3)
            [[ -z "$socket_gid" ]] && socket_gid="999"
        fi
        tagsManagerUpdateUniversalTag "$full_file_path" "SOCKET_GID_TAG" "$socket_gid"
    fi
}
