#!/bin/bash

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

# Actually applies the evaluated configuration, invoking each component's
# apply_* function (see any scripts/NN-* file for the check_*/apply_*
# convention). Its read-only counterpart, `check`, verifies the same
# configuration without changing anything, from the same files' check_*
# functions. The scripts/NN-* files only define functions; nothing runs
# them directly.
#
# Takes optional component names to apply only those (see --help, or
# scripts/libcc's cc_parse_args) - e.g. for diagnosing a single component.
#
# Dispatch is driven entirely by filename: only scripts/NN-* (a two-digit
# ordering prefix, e.g. 10-, 20-, 21-) are run, in the sorted order bash's
# own pathname expansion guarantees (POSIX requires filename-generation
# matches to be sorted by the current collating sequence) - unlike `find`,
# whose traversal order reflects raw directory/readdir order, which is
# filesystem-implementation-defined and not something to rely on (verified:
# on this box's btrfs, `find` returns entries in creation order, not
# alphabetical order). scripts/libcc and any file not following this
# naming are deliberately excluded. Inclusion doesn't depend on the
# executable bit either - the files are sourced, not executed - which is
# how scripts/services once went unnoticed as silently skipped.

# Journal identifier (SYSLOG_IDENTIFIER) everything a run logs under:
#   journalctl -t certification-sles-eal4            every run, oldest first
#   journalctl -t certification-sles-eal4 -p err     failures only
#   journalctl -t certification-sles-eal4 --grep '^71-config-permissions:'
CC_JOURNAL_ID="certification-sles-eal4"

# Every line of output is attributed to whoever produced it: apply's own
# lines carry "apply: " (cc_say), and every line a component produces - its
# own messages and the output of every tool it calls alike - carries
# "<component>: ", added by cc_prefix as that component's output passes
# through. Those are the only two places a prefix is written; the
# components themselves print plain lines.
cc_say() {
	echo "apply: $*"
}

cc_prefix() {
	sed -u "s|^|$1: |"
}

# Prefix each line with a syslog priority for systemd-cat's --level-prefix:
# err (3) for FAILED:/FAILURE:/ERROR: lines, notice (5) for NOTE: lines,
# info (6, systemd-cat's default) otherwise - so `journalctl -p err` finds
# failures without reading every line. A line that happens to start with
# something that looks like such a prefix itself (e.g. a tool printing
# "<1>") is passed through as info, unchanged.
cc_journal_priority() {
	sed -u -E \
		-e '/^<[0-7]>/{s/^/<6>/;b}' \
		-e '/^[^ ]+: (FAILED|FAILURE|ERROR)/{s/^/<3>/;b}' \
		-e '/^[^ ]+: NOTE:/s/^/<5>/'
}

# ERR trap handler inside each component's subshell (see cc_run_component).
# Names the command that failed and where, since many commands fail without
# printing anything themselves - a bare exit status leaves no way to tell
# from the log what actually went wrong. Only useful together with the
# `set -E` (errtrace) every scripts/NN-* file declares: without it, bash
# doesn't run the ERR trap inside functions at all, so a command failing
# inside apply_* would make `set -e` end the component silently.
# `set -E` also hands this trap to subshells within the component - command
# substitutions and `< <(...)` process substitutions alike. Those only exit
# with the failing status, the way `set -e` would anyway, and leave
# reporting to the component itself: anything printed there would land in
# whatever the caller reads from that subshell (e.g. a list of grub.cfg
# paths), and a failing command substitution is reported anyway, as the
# assignment that contains it.
# A function's own deliberate `return N` arrives here too: an apply_*
# function that already printed its own FAILED line, or one returning 2
# (applied, reboot required - not an error at all). Neither needs naming.
# $1: exit code, $2: failed command, $3: file it's in, $4: line number
cc_on_err() {
	local rc=$1
	local cmd=$2
	local src=$3
	local line=$4

	if [ "$BASH_SUBSHELL" -gt "$CC_COMPONENT_SUBSHELL" ]; then
		exit "$rc"
	fi
	case "$cmd" in
	return | return\ *) ;;
	*) echo "ERROR: '$cmd' failed with exit code $rc ($(basename "$src") line $line)" ;;
	esac
	exit "$rc"
}

# Run one component's apply_* function in a subshell of its own, so its
# shell options (`set -Eeuo pipefail`, declared by the file itself), trap
# and variables stay its own, as if it were a separate script. Its output
# goes through cc_prefix; the pipeline only finishes once the component has
# exited and its last line has passed through, so the next component's
# output never interleaves with this one's. The function's return value is
# the outcome, the convention `check` uses too: 0 compliant, 1 a failure, 2
# applied correctly but in effect only after a reboot. Returns the
# component's exit status, not cc_prefix's.
# $1: path of the scripts/NN-* file
cc_run_component() {
	local script=$1
	local name
	name=$(basename "$script")

	(
		CC_COMPONENT_SUBSHELL=$BASH_SUBSHELL
		trap 'cc_on_err $? "$BASH_COMMAND" "${BASH_SOURCE[0]}" "$LINENO"' ERR
		# shellcheck source=/dev/null
		. "$script"
		if ! declare -F "apply_${name//-/_}" >/dev/null; then
			echo "ERROR: defines no apply_${name//-/_} function - a naming mismatch in this package itself"
			exit 1
		fi
		"apply_${name//-/_}"
	) 2>&1 | cc_prefix "$name"
	return "${PIPESTATUS[0]}"
}

# Final summary, from the outcomes the dispatch loop below collected:
# CC_FAILED_SCRIPTS (any status other than 0 or 2) and CC_REBOOT_SCRIPTS
# (status 2). Names every component in each list, since a summary that
# only says "at least one error" leaves the reader to guess which of the
# lines above it was the failure. Exits 1 if anything failed, 2 if
# something only still needs a reboot, which is always the case in a chroot.
cc_report() {
	local reboot=0
	if [ "${#CC_REBOOT_SCRIPTS[@]}" -gt 0 ] || cc_in_chroot; then
		reboot=1
	fi

	if [ "${#CC_REBOOT_SCRIPTS[@]}" -gt 0 ]; then
		cc_say "NOTE: reboot required before fully in effect: ${CC_REBOOT_SCRIPTS[*]}"
	fi

	if [ "${#CC_FAILED_SCRIPTS[@]}" -gt 0 ]; then
		cc_say "FAILURE: CC configuration failed in: ${CC_FAILED_SCRIPTS[*]}"
		cc_say "FAILURE: see the lines above prefixed with those names (also: journalctl -t $CC_JOURNAL_ID)"
		if [ "${TRANSACTIONAL_UPDATE:-}" = true ]; then
			cc_say "FAILURE: transactional-update keeps this snapshot anyway, as the default for the next boot; 'transactional-update rollback' discards it"
		fi
		cc_say "FAILURE: the system is NOT in the evaluated configuration"
		exit 1
	fi

	# The daily transactional-update.service starts its snapshot from the
	# booted one, without --continue, so if it runs before the reboot, the
	# next boot uses its snapshot and these changes drop out.
	if [ "${TRANSACTIONAL_UPDATE:-}" = true ]; then
		cc_say "NOTE: reboot soon: an automatic update (transactional-update.timer) that runs before the reboot starts from the running system and leaves these changes out; check after the reboot shows whether they are in effect"
	fi

	# A run limited to selected components (see cc_parse_args) can't claim
	# anything about the configuration as a whole - only about what it ran.
	if [ "$CC_SUBSET" -eq 1 ]; then
		if [ "$reboot" -eq 1 ]; then
			cc_say "Selected components applied, but a reboot is required before they are fully in effect; the rest of the configuration was not checked (run apply without arguments for that)"
			exit 2
		fi
		cc_say "Selected components applied successfully; the rest of the configuration was not checked (run apply without arguments for that)"
		exit 0
	fi

	if [ "$reboot" -eq 1 ]; then
		cc_say "Common Criteria Evaluated Configuration: applied, but a reboot is required before it is fully in effect"
		exit 2
	fi

	cc_say "Common Criteria Evaluated Configuration: successfully established"
}

# On a read-only root (see cc_transactional_system), changes can only go
# into a new snapshot that becomes the default at the next boot, and that is
# the administrator's explicit step, as for packages. Inside the snapshot,
# the components behave as in any chroot.
# /home isn't mounted there, so 20-config-sshd's warning about
# authorized_keys that sshd will reject runs here, on the running system.
cc_refuse_read_only_root() {
	local script
	for script in "${CC_SELECTED_SCRIPTS[@]}"; do
		if [ "$(basename "$script")" = 20-config-sshd ]; then
			(
				# shellcheck source=/dev/null
				. "$script"
				warn_stranded_keys_20_config_sshd
			) 2>&1 | cc_prefix 20-config-sshd
		fi
	done
	cc_say "the root filesystem is read-only: changes go into a new snapshot, in effect after the next boot. Run:"
	cc_say "  transactional-update --continue run /usr/lib/common-criteria/apply${*:+ $*}"
	cc_say "then reboot. --continue builds on a snapshot that already waits for the next boot (e.g. an update) instead of leaving it out."
	cc_say "FAILURE: nothing was applied"
	exit 1
}

cc_parse_args "$@"
cc_require_root

if cc_transactional_system && ! cc_in_chroot; then
	cc_refuse_read_only_root "$@"
fi

# Copy all output from here on into the journal, while still showing it on
# the terminal. The journal keeps every run until its own size limits
# expire it, so re-running apply never overwrites the record of an earlier
# run. tee's -p keeps the terminal output going even if the journal pipe
# ever breaks.
# The process substitutions below leave a pipe open as file descriptor 63,
# which every tool this run starts inherits. LVM tools (grub2-mkconfig and
# grub2-probe call vgs on an LVM root) warn about any unexpected descriptor,
# dozens of times per run.
export LVM_SUPPRESS_FD_WARNINGS=1
if [ -S /run/systemd/journal/stdout ]; then
	exec > >(tee -p >(cc_journal_priority | systemd-cat -t "$CC_JOURNAL_ID" --level-prefix=true)) 2>&1
else
	cc_say "WARNING: journald not reachable - this run is not being logged"
fi

# The installed package version marks where each run starts in the journal,
# and tells whoever reads a log which build it came from.
cc_version=$(rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}' certification-sles-eal4 2>/dev/null) ||
	cc_version="package version unknown"
if [ "$CC_SUBSET" -eq 1 ]; then
	cc_say "starting, $cc_version - selected components only: $*"
else
	cc_say "starting, $cc_version"
fi

CC_FAILED_SCRIPTS=()
CC_REBOOT_SCRIPTS=()
for script in "${CC_SELECTED_SCRIPTS[@]}"; do
	name=$(basename "$script")
	cc_say "applying $name"
	cc_run_component "$script"
	rc=$?
	if [ "$rc" -eq 2 ]; then
		cc_say "NOTE: $name applied, but a reboot is required before it is fully in effect"
		CC_REBOOT_SCRIPTS+=("$name")
	elif [ "$rc" -ne 0 ]; then
		cc_say "FAILED: $name (exit status $rc)"
		CC_FAILED_SCRIPTS+=("$name")
	fi
done

cc_report
