#!/bin/bash
set -e

GROUP="iso-builder"

if [ -z "$PKEXEC_UID" ]; then
    echo "This script must be run via pkexec"
    exit 1
fi

CALLER_USER="$(id -nu "$PKEXEC_UID")"

# 1. Create group if missing
if ! getent group "$GROUP" >/dev/null; then
    echo "Creating group: $GROUP"
    groupadd "$GROUP"
fi

# 2. Check if user is in group
if id -nG "$CALLER_USER" | grep -qw "$GROUP"; then
    echo "User $CALLER_USER already in group $GROUP"
    exit 0
else
    echo "Adding $CALLER_USER to group $GROUP"
    usermod -aG "$GROUP" "$CALLER_USER"
    echo "User added. Logout/login required."
    exit 100
fi
