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

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

# SLES16 ships its default login.defs at /usr/etc/login.defs (the login_defs
# package's libeconf-based vendor file) and merges local overrides from
# /etc/login.defs.d/*.defs - libeconf requires the drop-in suffix to match
# the vendor file's own extension (login.defs -> .defs), not the more common
# .conf.
LOGINDEFS_VENDOR_CONFIG="/usr/etc/login.defs"
LOGINDEFS_DROPIN_DIR="/etc/login.defs.d"
LOGINDEFS_DROPIN="$LOGINDEFS_DROPIN_DIR/50-cc.defs"

check_40_config_logindefs() {
	if [ ! -f "$LOGINDEFS_DROPIN" ]; then
		echo "$LOGINDEFS_DROPIN missing"
		return 1
	fi
	if ! grep -q "^UMASK 077$" "$LOGINDEFS_DROPIN"; then
		echo "$LOGINDEFS_DROPIN missing 'UMASK 077'"
		return 1
	fi
}

apply_40_config_logindefs() {
	[ -f "$LOGINDEFS_VENDOR_CONFIG" ] || {
		cc_echo "FAILED: $LOGINDEFS_VENDOR_CONFIG missing - is login_defs installed?"
		return 1
	}

	if check_40_config_logindefs; then
		cc_echo "$LOGINDEFS_DROPIN already installed"
		return 0
	fi

	mkdir -p "$LOGINDEFS_DROPIN_DIR"

	# The guide's "Discretionary Access Control" section MUSTs a umask that
	# includes at least the 002 bit (no write access for others) and
	# RECOMMENDS 027 (group read/execute, no access for others); 077 (no
	# access for group or others at all) satisfies and exceeds both.
	cat > "$LOGINDEFS_DROPIN" <<'EOF'
# Common Criteria evaluated configuration - managed by certification-sles-eal4.
# Do not edit; changes here will be overwritten. Add local exceptions in a
# file that sorts after this one in /etc/login.defs.d/ (keep the .defs
# suffix - libeconf ignores drop-ins with any other extension).
UMASK 077
EOF
	chmod 644 "$LOGINDEFS_DROPIN"
	cc_echo "Installed $LOGINDEFS_DROPIN"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
	cc_start_logging
	trap 'cc_exit $?' ERR
	apply_40_config_logindefs
	cc_exit 0
fi
