#!/usr/bin/env bash
set -e

LOCAL_GROUP="baseusers"

# Ensure local group exists
if ! getent group "$LOCAL_GROUP" >/dev/null; then
    groupadd "$LOCAL_GROUP"
fi

# Detect active user (works for SSH + console)
CURRENT_USER=$(who | awk '{print $1}' | head -n 1)

if [ -z "$CURRENT_USER" ]; then
    exit 0
fi

# Ensure user exists
if ! id "$CURRENT_USER" >/dev/null 2>&1; then
    exit 0
fi

# Check if user is in FreeIPA BaseUser group
if id "$CURRENT_USER" | grep -q "BaseUser"; then

    # Add to local group if missing
    if ! id "$CURRENT_USER" | grep -q "$LOCAL_GROUP"; then
        usermod -aG "$LOCAL_GROUP" "$CURRENT_USER"
    fi
fi
