#!/bin/sh
# Case: On NixOS, output uses Nix expression syntax with boot.blacklistedKernelModules
set -eu

CASE_NAME=nixos-nix-output
export CASE_NAME

# shellcheck source=tests/lib/case-env.sh disable=SC1091
. "$(dirname "$0")/../lib/case-env.sh"
# shellcheck source=tests/lib/case-tree.sh disable=SC1091
. "$REPO_ROOT/tests/lib/case-tree.sh"
# shellcheck source=tests/lib/assert.sh disable=SC1091
. "$REPO_ROOT/tests/lib/assert.sh"

# Force NixOS mode via environment variable
export MODULEJAIL_ON_NIXOS=1

# Use the synthetic module tree from case-tree.sh
export MODULEJAIL_MODULES_ROOT="$CASE_MODULES_ROOT"

OUT=$CASE_TMP/test-output.nix
"$MODULEJAIL_BIN" --dry-run -o "$OUT" > "$CASE_TMP/stdout" 2> "$CASE_TMP/stderr" || \
    case_fail "modulejail exited $? (expected 0); stderr=$(cat "$CASE_TMP/stderr")"

# --- Verify Nix expression syntax ---
# Function header
assert_grep '^{ \.\.\. }:' "$CASE_TMP/stderr" nixos-function-header

# boot.blacklistedKernelModules attribute
assert_grep 'boot\.blacklistedKernelModules = \[' "$CASE_TMP/stderr" nixos-nix-attr-opening
assert_grep '^  \];' "$CASE_TMP/stderr" nixos-nix-attr-closing

# Quoted module names with 2-space indent
assert_grep '^  "' "$CASE_TMP/stderr" nixos-nix-modules-indented
# Specific modules from the synthetic tree (not in baseline, so they should be blacklisted)
assert_grep '^  "dummy_1"' "$CASE_TMP/stderr" nixos-module-dummy_1-quoted
assert_grep '^  "dummy_2"' "$CASE_TMP/stderr" nixos-module-dummy_2-quoted
assert_grep '^  "sctp"' "$CASE_TMP/stderr" nixos-module-sctp-quoted

# --- Verify NO modprobe.d syntax ---
if grep -qE '^install ' "$CASE_TMP/stderr"; then
    case_fail "Found modprobe.d install directive in NixOS output"
fi
if grep -qE '/bin/true' "$CASE_TMP/stderr"; then
    case_fail "Found /bin/true in NixOS output"
fi
if grep -qE '# modulejail ' "$CASE_TMP/stderr"; then
    case_fail "Found modprobe.d comment in NixOS output"
fi

# --- Verify NixOS header comments ---
assert_grep '^# NixOS modulejail blacklist' "$CASE_TMP/stderr" nixos-header-title
assert_grep '^# Generated by modulejail' "$CASE_TMP/stderr" nixos-header-generated
assert_grep '^# Profile:' "$CASE_TMP/stderr" nixos-header-profile
assert_grep '^# Kernel:' "$CASE_TMP/stderr" nixos-header-kernel
assert_grep '^# Fingerprint:' "$CASE_TMP/stderr" nixos-header-fingerprint
assert_grep '^# Invocation:' "$CASE_TMP/stderr" nixos-header-invocation
assert_grep '^# Do not edit by hand' "$CASE_TMP/stderr" nixos-header-do-not-edit

# --- Verify stdout has dry-run summary ---
assert_grep 'would blacklist.*modules' \
    "$CASE_TMP/stdout" nixos-dry-run-summary

case_pass
