#!/bin/bash

# Both `apply` (which writes to /etc, /var/log, and calls systemctl) and
# `check` (which, despite being read-only, still needs to read root-only
# files like grub.cfg - typically mode 600 - to check them) require root.
# Without this guard, a non-root `check` invocation doesn't fail outright:
# individual check_* functions instead report spurious FAILs from
# "Permission denied" reading a file they can't access, which looks exactly
# like a real compliance finding rather than the actual problem (forgetting
# sudo).
cc_require_root() {
	if [ "$(id -u)" -ne 0 ]; then
		echo "$(basename "$0") must be run as root" >&2
		exit 1
	fi
}

# Is this running in a chroot, configuring a system that isn't the running
# one: a transactional-update snapshot (tukit sets TRANSACTIONAL_UPDATE=true
# in the chroot it runs commands in), an installer's target or an image
# being built? There, changes take effect only once that system is booted,
# systemctl ignores commands that act on running units (is-active, show,
# daemon-reload, --now) and reports success, and /proc describes the running
# system.
cc_in_chroot() {
	[ "${TRANSACTIONAL_UPDATE:-}" = true ] || systemd-detect-virt --quiet --chroot
}

# Is the root filesystem a read-only btrfs snapshot that only
# transactional-update changes (SL Micro)? The same test
# transactional-update makes.
cc_transactional_system() {
	[ "$(btrfs property get / ro 2>/dev/null)" = "ro=true" ]
}

# Numbers of the booted and the default (next boot) btrfs snapshot, empty if
# the root filesystem doesn't boot from snapper snapshots.
cc_snapshot_booted() {
	findmnt -fno FSROOT / 2>/dev/null | sed -n 's|.*/\.snapshots/\([0-9][0-9]*\)/snapshot$|\1|p' || true
}

cc_snapshot_default() {
	btrfs subvolume get-default / 2>/dev/null | sed -n 's|.*\.snapshots/\([0-9][0-9]*\)/snapshot$|\1|p' || true
}

# Is $1 a stub that only hands over to another grub.cfg? shim-install writes
# one into the ESP (search for the filesystem holding /boot/grub2, set
# prefix, `source "${prefix}/grub.cfg"`), and rewrites it on every run - e.g.
# from fips-mode-setup's `pbl --install`, or a shim/grub2 update. A stub
# carries no kernel command line of its own, so it must neither be required
# to contain a parameter nor be overwritten by grub2-mkconfig.
cc_grub_cfg_is_stub() {
	local f="$1"
	if grep -qE '^[[:space:]]*(menuentry|linux|linuxefi)[[:space:]]' "$f"; then
		return 1
	fi
	grep -qE '^[[:space:]]*(source|configfile)[[:space:]].*/grub\.cfg' "$f"
}

# List every grub.cfg that holds a kernel command line this system's
# bootloader might use: the standard /boot/grub2/grub.cfg, plus any
# vendor-specific EFI one under the ESP that is a full config rather than a
# stub (the directory name varies by product - "sles", "sle_rt", ... -
# globbed rather than hardcoded, like the guide's own "test -e ... &&
# grub2-mkconfig" instructions). An Agama-installed box can have an ESP
# mounted at /boot/efi even while booting via BIOS, so checking only one
# path would be an unverified assumption about the boot path.
cc_grub_cfg_paths() {
	local f
	if [ -e "/boot/grub2/grub.cfg" ]; then
		echo "/boot/grub2/grub.cfg"
	fi
	for f in /boot/efi/EFI/*/grub.cfg; do
		if [ -e "$f" ] && ! cc_grub_cfg_is_stub "$f"; then
			echo "$f"
		fi
	done
}

# Regenerate every grub.cfg cc_grub_cfg_paths finds.
cc_grub_regenerate() {
	if ! command -v grub2-mkconfig >/dev/null 2>&1; then
		cc_echo "grub2-mkconfig not found - skipping grub.cfg regeneration"
		return 0
	fi
	local f
	while IFS= read -r f; do
		grub2-mkconfig -o "$f"
	done < <(cc_grub_cfg_paths)
}

# Is $1 one of the kernel parameters in GRUB_CMDLINE_LINUX or
# GRUB_CMDLINE_LINUX_DEFAULT of /etc/default/grub (not in a comment or another
# variable)? The file is shell syntax, read the way grub2-mkconfig reads it.
cc_grub_default_has() {
	local param="$1"
	(
		set +eu
		GRUB_CMDLINE_LINUX=""
		GRUB_CMDLINE_LINUX_DEFAULT=""
		# shellcheck source=/dev/null
		. /etc/default/grub >/dev/null 2>&1
		[[ " $GRUB_CMDLINE_LINUX $GRUB_CMDLINE_LINUX_DEFAULT " == *" $param "* ]]
	)
}

# Does every grub.cfg cc_grub_cfg_paths finds contain $1? False (with
# nothing printed) if there are no such files at all - callers should
# already have confirmed $GRUB_DEFAULT/grub2-mkconfig exist before relying
# on this meaning anything.
cc_grub_cfg_has() {
	local param="$1"
	local f
	local found=0
	while IFS= read -r f; do
		found=1
		cc_grub_cfg_file_has "$f" "$param" || return 1
	done < <(cc_grub_cfg_paths)
	[ "$found" = 1 ]
}

# Replace a given file with a new file and back up the old file
# The function ensures that the permissions are kept
# $1: new file that will be overwritten over the old old one (i.e. source)
# $2: file to be replaced (i.e. destination)
cc_replace() {
	local src=$1
	local dst=$2
	local date
	local mode
	local owner

	if [ -z "$src" ] || [ -z "$dst" ]; then
		echo "Missing input parameters" >&2
		return 1
	fi

	if [ ! -e "$src" ] || [ ! -e "$dst" ]; then
		echo "Files missing" >&2
		return 1
	fi

	date=$(date +"%Y%m%d%H%M%S")
	mode=$(stat -L -c '%a' "$dst")
	owner=$(stat -L -c '%U:%G' "$dst")

	# Create backup
	cp "$dst" "$dst.$date"
	chmod "$mode" "$dst.$date"
	chown "$owner" "$dst.$date"

	# copy the new file
	cp -p "$src" "$dst"
	chmod "$mode" "$dst"
	chown "$owner" "$dst"
}

# Every dispatchable script (scripts/NN-*: a two-digit ordering prefix, e.g.
# 10-, 20-, 21-), in the sorted order bash's own pathname expansion
# guarantees (POSIX requires filename-generation matches to be sorted by the
# current collating sequence). scripts/libcc itself, and anything else not
# following this naming, is deliberately excluded.
CC_SCRIPTS_DIR="/usr/lib/common-criteria/scripts"
cc_all_scripts() {
	local script
	shopt -s nullglob
	for script in "$CC_SCRIPTS_DIR"/[0-9][0-9]-*; do
		if [ -f "$script" ]; then
			echo "$script"
		fi
	done
}

# Shared command-line handling for `apply` and `check`:
#   (no arguments)  every component, i.e. the whole evaluated configuration
#   NAME...         only these components - a script's full name
#                   (71-config-permissions) or the same without its ordering
#                   prefix (config-permissions); they still run in dispatch
#                   order, not the order given, and each at most once
#   --list          print every component name and exit
#   -h, --help      print usage and exit
# Sets CC_SELECTED_SCRIPTS (array of paths) and CC_SUBSET (1 if only some
# components were selected, else 0). An unknown option or component name
# exits 1 rather than silently selecting nothing.
cc_parse_args() {
	local arg script name matched
	local -a names=()
	local -A seen=()

	for arg in "$@"; do
		case "$arg" in
		-h | --help)
			cat <<EOF
Usage: $(basename "$0") [NAME...]
       $(basename "$0") --list

Without arguments, $(basename "$0") covers every component of the evaluated
configuration. Given one or more component names (e.g. 71-config-permissions,
or just config-permissions), only those are covered - useful for diagnosing
a single component, but the result then says nothing about the rest of the
configuration. Components assume the ones before them have been applied
(e.g. 71-config-permissions restricts sudo/su to the trusted group, which
10-add_user_to_trusted_group must already have added the administrator to).
EOF
			exit 0
			;;
		--list)
			while IFS= read -r script; do
				basename "$script"
			done < <(cc_all_scripts)
			exit 0
			;;
		-*)
			echo "$(basename "$0"): unknown option '$arg' (see --help)" >&2
			exit 1
			;;
		*)
			names+=("$arg")
			;;
		esac
	done

	CC_SELECTED_SCRIPTS=()
	CC_SUBSET=0
	if [ "${#names[@]}" -gt 0 ]; then
		CC_SUBSET=1
	fi
	while IFS= read -r script; do
		name=$(basename "$script")
		if [ "$CC_SUBSET" -eq 0 ]; then
			CC_SELECTED_SCRIPTS+=("$script")
			continue
		fi
		matched=0
		for arg in "${names[@]}"; do
			if [ "$arg" = "$name" ] || [ "$arg" = "${name#[0-9][0-9]-}" ]; then
				seen[$arg]=1
				matched=1
			fi
		done
		if [ "$matched" -eq 1 ]; then
			CC_SELECTED_SCRIPTS+=("$script")
		fi
	done < <(cc_all_scripts)

	for arg in "${names[@]}"; do
		if [ -z "${seen[$arg]:-}" ]; then
			echo "$(basename "$0"): unknown component '$arg' (see --list)" >&2
			exit 1
		fi
	done
}
