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

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

# Same vendor-file + native Include drop-in mechanism as scripts/20-config-sshd,
# for the client-side configuration.
SSH_VENDOR_CONFIG="/usr/etc/ssh/ssh_config"
SSH_DROPIN_DIR="/etc/ssh/ssh_config.d"
SSH_DROPIN="$SSH_DROPIN_DIR/50-cc.conf"

check_21_config_ssh_client() {
	if [ ! -f "$SSH_DROPIN" ]; then
		echo "$SSH_DROPIN missing"
		return 1
	fi
	if ! grep -q "ForwardAgent no" "$SSH_DROPIN"; then
		echo "$SSH_DROPIN missing 'ForwardAgent no'"
		return 1
	fi
	if ! ssh -T -F "$SSH_VENDOR_CONFIG" -G localhost >/dev/null 2>&1; then
		echo "merged ssh_config fails to parse ('ssh -G' check)"
		return 1
	fi
}

apply_21_config_ssh_client() {
	[ -f "$SSH_VENDOR_CONFIG" ] || {
		cc_echo "OpenSSH client does not appear to be installed ($SSH_VENDOR_CONFIG missing) - skipping configuration"
		return 0
	}

	if check_21_config_ssh_client; then
		cc_echo "$SSH_DROPIN already installed and verified"
		return 0
	fi

	mkdir -p "$SSH_DROPIN_DIR"

	cat > "$SSH_DROPIN" <<'EOF'
# Common Criteria evaluated configuration - managed by certification-sles-eal4.
# Do not edit; changes here will be overwritten. ssh applies the first value
# it encounters for each keyword and ignores later ones (confirmed: an
# earlier-sorting drop-in's ForwardAgent wins over a later one's), so a
# local exception needs a file that sorts BEFORE this one in
# /etc/ssh/ssh_config.d/, not after.
Host *
	ForwardAgent no
	UseRoaming no
EOF
	chmod 644 "$SSH_DROPIN"
	cc_echo "Installed $SSH_DROPIN"

	# Validate the full merged configuration the same way scripts/20-config-sshd
	# does for the server side. UseRoaming is a deprecated no-op on current
	# OpenSSH (client-side roaming was removed after a past CVE) but is kept
	# here to match the evaluated configuration's letter; it is harmless.
	check_21_config_ssh_client || {
		cc_echo "FAILED: ssh_config does not parse cleanly after installing $SSH_DROPIN"
		return 1
	}
	cc_echo "$SSH_DROPIN installed and verified"
}

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