#!/bin/bash
set -Eeuo 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
		if cc_is_chroot; then
			return 0
		fi
		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
		echo "FAILED: no user with UID 1000 found, cannot add anyone to the trusted group"
		if cc_in_chroot; then
			echo "FAILED: in a chroot (installer, image build) the administrator may not exist yet: run apply again once the system is booted and the account exists"
		fi
		return 1
	fi

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

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