#!/bin/bash

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

cc_parse_args "$@"
cc_require_root

# Read-only counterpart to `apply`: reports whether the evaluated
# configuration is currently in place, without changing anything. Sources
# every scripts/NN-* file for its function definitions and calls only its
# check_* function, never apply_*, so this is safe to invoke as often as
# wanted (e.g. once per login), unlike `apply`. Takes
# the same optional component names as `apply` to check only those (see
# --help, or scripts/libcc's cc_parse_args).
#
# Deliberately does not log to the journal the way `apply` does: this is
# meant to be cheap and frequent, and routing every check there would mix
# routine verification noise into what's otherwise `apply`'s own operation
# record.
#
# A script's check_* function name is derived mechanically from its own
# filename (20-config-sshd -> check_20_config_sshd, just s/-/_/ plus a
# prefix) rather than kept as a separate, hand-maintained list here - the
# same reason `apply`'s own dispatch loop matches scripts/NN-* by glob
# instead of naming each one: a new or renamed script picks this up for
# free, with no second place to remember to update.
# PASS is right-justified (indented) and FAIL/ERROR are left-justified (flush
# against the margin) in the same fixed-width field, on purpose: PASS is the
# expected, common case, so pushing it inward leaves a blank left margin that
# any FAIL or ERROR visibly breaks - scanning down the left edge finds a
# problem line without reading every word.
# Each check_* function prints one line explaining itself when it fails (see
# any scripts/NN-* file) - shown indented under its FAIL, rather than
# discarded, so a failure is diagnosable from `check`'s own output alone,
# without having to go read the script's source.
#
# check_* can also return 2 - applied correctly, but needs a reboot before
# it's actually in effect (`apply`'s own convention) - reported as REBOOT
# rather than FAIL, since nothing is actually wrong. $overall only ever moves
# from 0 towards whichever is worse (a single FAIL/ERROR anywhere makes the
# whole result 1, even if other scripts are merely REBOOT), never backwards.
# $1: label, $2: PASS, REBOOT, FAIL or ERROR, $3: reason lines (may be empty)
print_one() {
	if [ "$2" = PASS ]; then
		printf '%6s  %s\n' "$2" "$1"
	else
		printf '%-6s  %s\n' "$2" "$1"
	fi
	[ -n "$3" ] && printf '        %s\n' "${3//$'\n'/$'\n        '}"
	case "$2" in
	PASS) ;;
	REBOOT)
		if [ "$overall" -eq 0 ]; then
			overall=2
		fi
		;;
	*) overall=1 ;;
	esac
}

# Runs one component's check_* on the running system, into status[$1] and
# reason[$1].
check_one() {
	local label="$1"
	local fn="$2"
	local rc

	if ! declare -F "$fn" >/dev/null; then
		status[$label]=ERROR
		reason[$label]="$fn not defined - a naming mismatch in check/apply itself, not a compliance finding"
		return
	fi

	# Every scripts/NN-* file we sourced above declares `set -Eeuo pipefail` at
	# its own top level, which leaks into this process from the moment the
	# first one is sourced (sourcing isn't scoped - shell options it sets
	# apply here too) and never turns back off. A bare `reason=$(...)`
	# assignment is not exempt from that, so it would abort this whole
	# script the instant any check_* returns non-zero - `|| rc=$?` keeps
	# this exempt the same way every apply_* guard already relies on.
	rc=0
	reason[$label]=$("$fn" 2>&1) || rc=$?
	case "$rc" in
	0) status[$label]=PASS ;;
	2) status[$label]=REBOOT ;;
	*) status[$label]=FAIL ;;
	esac
}

# On a transactional system (SL Micro), the next boot uses the default
# snapshot, which apply (run through transactional-update) or an update may
# have changed since the running system booted - or replaced with one that
# lacks apply's changes. Runs that snapshot's own `check` in a chroot, in a
# private mount namespace, so all mounts vanish with it, and fills
# next_status and next_reason from its output. In the chroot, components
# stop at the configuration (see cc_in_chroot), so REBOOT there means "in
# place once booted". The running system's /var is shared by all snapshots
# and mounted read-only; /run and /tmp get a tmpfs.
# $1: snapshot number, $@ after it: component names, as given to check
check_next_boot() {
	local snap=$1
	shift
	local root="/.snapshots/$snap/snapshot"
	local out line label
	local -a names=()

	if [ ! -x "$root/usr/lib/common-criteria/check" ]; then
		for label in "${labels[@]}"; do
			next_status[$label]=FAIL
			next_reason[$label]="certification-sles-eal4 is not installed in snapshot $snap"
		done
		return
	fi

	# shellcheck disable=SC2016 # expanded by the inner bash
	out=$(unshare -m bash -c '
		set -e
		root=$1
		shift
		mount -t proc proc "$root/proc"
		mount -t sysfs sysfs "$root/sys"
		mount --bind /dev "$root/dev"
		mount --bind /var "$root/var"
		mount -o remount,bind,ro "$root/var"
		mount -t tmpfs cc-check "$root/run"
		mount -t tmpfs cc-check "$root/tmp"
		if mountpoint -q /boot/efi; then
			mount --bind /boot/efi "$root/boot/efi"
			mount -o remount,bind,ro "$root/boot/efi"
		fi
		exec chroot "$root" /usr/lib/common-criteria/check "$@"
	' bash "$root" "$@" 2>&1) || true

	while IFS= read -r line; do
		if [[ "$line" =~ ^\ *(PASS|REBOOT|FAIL|ERROR)\ +([^ ]+) ]]; then
			label=${BASH_REMATCH[2]}
			next_status[$label]=${BASH_REMATCH[1]}
			next_reason[$label]=""
			names+=("$label")
		elif [[ "$line" =~ ^\ {8}(.*) ]] && [ "${#names[@]}" -gt 0 ]; then
			label=${names[-1]}
			next_reason[$label]+="${next_reason[$label]:+$'\n'}${BASH_REMATCH[1]}"
		fi
	done <<<"$out"

	for label in "${labels[@]}"; do
		if [ -z "${next_status[$label]:-}" ]; then
			next_status[$label]=FAIL
			next_reason[$label]="not checked in snapshot $snap: ${out##*$'\n'}"
		fi
	done
}

declare -A status=() reason=() next_status=() next_reason=()
labels=()
overall=0

# The loop variable is deliberately not a generic name like "script": each
# file sourced below runs its own top level in this same process, so any
# variable it sets there lands in this scope too.
for cc_component in "${CC_SELECTED_SCRIPTS[@]}"; do
	name=$(basename "$cc_component")
	labels+=("$name")
	# shellcheck disable=SC1090
	. "$cc_component"
	check_one "$name" "check_${name//-/_}"
done

# When the next boot uses the booted snapshot, both views are the same, and
# a chroot into it would be one into the running root, which
# systemd-detect-virt --chroot doesn't recognize as a chroot.
cc_next_snapshot=""
if cc_transactional_system && ! cc_in_chroot; then
	cc_booted_snapshot=$(cc_snapshot_booted)
	cc_next_snapshot=$(cc_snapshot_default)
	if [ -z "$cc_next_snapshot" ]; then
		echo "NOTE: the snapshot for the next boot is unknown; only the running system is checked"
	elif [ "$cc_next_snapshot" = "$cc_booted_snapshot" ]; then
		echo "Booted snapshot: $cc_booted_snapshot; next boot: the same snapshot"
		cc_next_snapshot=""
	fi
fi

if [ -z "$cc_next_snapshot" ]; then
	for label in "${labels[@]}"; do
		print_one "$label" "${status[$label]}" "${reason[$label]}"
	done
else
	check_next_boot "$cc_next_snapshot" "$@"
	echo "Booted snapshot: $cc_booted_snapshot; next boot: snapshot $cc_next_snapshot"
	run_failed=0
	next_failed=0
	# Combined per component: the next boot decides whether it fails; if it
	# doesn't, a component the running system lacks is waiting for the
	# reboot.
	for label in "${labels[@]}"; do
		run=${status[$label]}
		next=${next_status[$label]}
		if [ "$run" = PASS ] && [ "$next" != FAIL ] && [ "$next" != ERROR ]; then
			print_one "$label" PASS ""
			continue
		fi
		if [ "$run" != PASS ] && [ "$run" != REBOOT ]; then
			run_failed=1
		fi
		if [ "${reason[$label]}" = "${next_reason[$label]}" ]; then
			detail="running system and next boot: ${reason[$label]}"
		else
			detail="running system: ${reason[$label]:-in place}"
			detail+=$'\n'"next boot: ${next_reason[$label]:-in place}"
		fi
		if [ "$run" = ERROR ] || [ "$next" = ERROR ]; then
			print_one "$label" ERROR "$detail"
		elif [ "$next" = FAIL ]; then
			print_one "$label" FAIL "$detail"
			next_failed=1
		else
			print_one "$label" REBOOT "$detail"
		fi
	done
fi

# A check limited to selected components can't claim anything about the
# configuration as a whole. render-banner only ever runs check without
# arguments, so the login banner always shows the whole-configuration line.
if [ "$CC_SUBSET" -eq 1 ]; then
	case "$overall" in
	0) echo "Selected components: in place (the rest of the configuration was not checked)" ;;
	2) echo "Selected components: applied, but a reboot is required before they are fully in effect" ;;
	*) echo "Selected components: NOT in place" ;;
	esac
	exit "$overall"
fi

case "$overall" in
0)
	echo "Common Criteria Evaluated Configuration: currently in place"
	;;
2)
	echo "Common Criteria Evaluated Configuration: applied, but a reboot is required before it is fully in effect"
	;;
*)
	if [ -n "$cc_next_snapshot" ] && [ "$run_failed" -eq 0 ] && [ "$next_failed" -eq 1 ]; then
		echo "Common Criteria Evaluated Configuration: NOT in place at the next boot - run /usr/lib/common-criteria/check for details, or /usr/lib/common-criteria/apply as root to fix"
	else
		echo "Common Criteria Evaluated Configuration: NOT currently in place - run /usr/lib/common-criteria/check for details, or /usr/lib/common-criteria/apply as root to fix"
	fi
	;;
esac

exit "$overall"
