#!/bin/bash
set -euo pipefail
shopt -s inherit_errexit

# shellcheck source=scripts/libcc
. /usr/lib/common-criteria/scripts/libcc

# This script adds the defined non-root user to the trusted group. The CC
# guidance's installation instructions assume the user created during
# installation gets UID 1000 (SLES's default UID_MIN) and should already be
# a trusted-group member for administrative access; this mirrors that.

check_10_add_user_to_trusted_group() {
	local ccuser
	ccuser=$(/usr/bin/id -nu 1000 2>/dev/null) || ccuser=""
	if [ -z "$ccuser" ]; then
		echo "no user with UID 1000 found"
		return 1
	fi
	if ! id -nG "$ccuser" 2>/dev/null | tr ' ' '\n' | grep -qx trusted; then
		echo "$ccuser is not a member of the trusted group"
		return 1
	fi
}

apply_10_add_user_to_trusted_group() {
	local ccuser
	ccuser=$(/usr/bin/id -nu 1000 2>/dev/null) || ccuser=""

	if [ -z "$ccuser" ]; then
		cc_echo "FAILED: no user with UID 1000 found, cannot add anyone to the trusted group"
		return 1
	fi

	if check_10_add_user_to_trusted_group; then
		cc_echo "$ccuser already in the trusted group"
		return 0
	fi

	usermod -a -G trusted "$ccuser"
	cc_echo "Added $ccuser (UID 1000) to the trusted group"
}

# Only run when executed directly (by `apply`, or by hand) -- sourcing this
# file for its function definitions alone must never change anything.
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
	cc_start_logging
	trap 'cc_exit $?' ERR
	apply_10_add_user_to_trusted_group
	cc_exit 0
fi
