#!/usr/bin/env bash
set -euo pipefail

# Run from the Shirudo checkout in WSL, after the article's root baseline probe.
# The caller runs as nobody *inside* the disposable VM. This is not a CVE exploit.

VM=${1:-}
COUNT=${2:-3}
PROBE=/workspace/shirudo/upatches/kernel-cve/sources/cve-2026-31431-crypto-algif-aead-copy-fail/reproducer/cve-2026-31431-splice-probe.py

if [[ ! $VM =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || [[ ! $COUNT =~ ^[1-6]$ ]] || [[ ! -f testing/Makefile ]]; then
  printf 'Usage (from the Shirudo checkout): bash attempt.sh VM_NAME [1-6 attempts]\n' >&2
  exit 2
fi

red= green= reset=
if [[ -t 1 && -z ${NO_COLOR:-} ]]; then
  red=$'\033[1;31m'
  green=$'\033[1;32m'
  reset=$'\033[0m'
fi

printf 'LOCAL CALLER  guest=nobody  target=%s\n' "$VM"
printf '32-byte pipe splice into AF_ALG. Indented syscall and SPLICE_* lines come from the VM.\n'
printf 'Attempt headings and coloured verdicts are added here in WSL.\n\n'

if ! prereq=$(make --no-print-directory -C testing vm-ssh VM_NAME="$VM" \
  VM_SSH_COMMAND="command -v runuser && command -v strace" 2>&1); then
  printf 'Could not reach the VM or confirm runuser and strace:\n%s\n' "$prereq" >&2
  exit 1
fi

for ((n = 1; n <= COUNT; n++)); do
  if ! output=$(make --no-print-directory -C testing vm-ssh VM_NAME="$VM" \
    VM_SSH_COMMAND="runuser -u nobody -- sh -c 'strace -qq -e trace=splice python3 $PROBE 2>&1'" 2>&1); then
    printf 'Attempt %02d: guest command failed:\n%s\n' "$n" "$output" >&2
    exit 1
  fi

  printf 'Attempt %02d\n' "$n"
  while IFS= read -r line; do
    case "$line" in
      *EACCES*|SPLICE_BLOCKED) printf '  %s%s%s\n' "$red" "$line" "$reset" ;;
      *'= 32'*|SPLICE_OK) printf '  %s%s%s\n' "$green" "$line" "$reset" ;;
      *) printf '  %s\n' "$line" ;;
    esac
  done <<< "$output"

  if grep -Fxq SPLICE_BLOCKED <<< "$output" && grep -Eq '^splice\(.*= -1 EACCES' <<< "$output"; then
    printf '  %s[ BLOCKED ]%s Local AF_ALG splice returned EACCES.\n\n' "$red" "$reset"
  elif grep -Fxq SPLICE_OK <<< "$output" && grep -Eq '^splice\(.*= 32' <<< "$output"; then
    printf '  %s[ ALLOWED ]%s The splice returned 32 bytes.\n\n' "$green" "$reset"
  else
    printf '  [ INCONCLUSIVE ] Check the raw result above.\n' >&2
    exit 1
  fi
done
