#!/usr/bin/env bash
# Install root-owned as /usr/local/sbin/devsecops-openscap-host on the RHEL TEST host.
# No caller-supplied arguments or environment-based profile selection.
set -euo pipefail
[[ "$EUID" == 0 && "$#" == 0 ]] || exit 2
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077
exec 9>/run/lock/devsecops-openscap.lock
flock -n 9 || { echo 'Another compliance scan is running' >&2; exit 2; }
. /etc/os-release
[[ "$ID" == rhel && "$VERSION_ID" == 9.6 ]] || exit 2
# Administrator: select an available profile using oscap info before installation.
profile=xccdf_org.ssgproject.content_profile_cis_server_l1
content=/usr/share/xml/scap/ssg/content/ssg-rhel9-ds.xml
work="$(mktemp -d /var/tmp/devsecops-openscap.XXXXXXXX)"
status=0
oscap xccdf eval --profile "$profile" --results "$work/results.xml" \
  --report "$work/report.html" "$content" > "$work/scan.log" 2>&1 || status=$?
python3 - "$work/results.xml" > "$work/coverage.log" 2>&1 <<'PY' || status=2
import sys, xml.etree.ElementTree as ET
from collections import Counter
r=ET.parse(sys.argv[1]).getroot()
values=[node.text for result in r.iter() if result.tag.endswith('}rule-result')
        for node in result if node.tag.endswith('}result')]
counts=Counter(values)
print(dict(counts))
# Fail incomplete assessments; a profile with no passing rules is not accepted.
if not counts['pass'] or any(counts[s] for s in ('fail','error','unknown','notchecked')):
    sys.exit(2)
PY
printf '%s\n' "$status" > "$work/exit-code.txt"
# SSH captures stdout as an evidence archive, even when compliance failed.
tar -C "$work" -czf - .
exit "$status"
