#!/bin/bash
#
# Common functions shared between MCP Gateway install and uninstall scripts

# Check if the aembit user group can be deleted.
is_group_empty() {
    local group_name=$1
    local gid members group_entry supplementary_members
    
    # Check if the group exists
    if ! group_entry=$(getent group "${group_name}" 2>/dev/null); then
        return 1
    fi
    
    # Parse group entry to check for supplementary members (4th field)
    # Format: groupname:password:gid:member1,member2,...
    supplementary_members=$(echo "${group_entry}" | cut -d":" -f4)
    if [ -n "${supplementary_members}" ]; then
        # Group has supplementary members, not empty
        return 1
    fi
    
    # Get the group id for the group
    gid=$(echo "${group_entry}" | cut -d":" -f3)
    
    # Check for users with this group as their primary GID, using NSS (getent)
    # Format: username:password:uid:gid:gecos:home:shell
    # Use grep to find lines where field 4 (gid) matches, then extract username (field 1)
    members=$(getent passwd 2>/dev/null | grep -E "^[^:]+:[^:]*:[^:]*:${gid}:" | cut -d: -f1)
    
    # If there are no users using gid as primary and no supplementary members, the group is empty
    [ -z "$members" ] && return 0
    
    return 1
}
