#!/usr/bin/env bash
# AAES sample-pack tamper demonstration.
#
# Downloads nothing and contacts no service. Run it inside the unpacked
# verification pack next to sample-export.jsonl, sample-pubkey.txt and the
# aaesctl binary for your platform:
#
#   chmod +x bin/aaesctl-$(uname -s | tr 'A-Z' 'a-z')-$(uname -m | sed -e 's/^x86_64$/amd64/' -e 's/^aarch64$/arm64/')
#   bash tamper-demo.sh
#
# On Windows, run it in Git Bash or WSL: the .exe suffix is added
# automatically and no chmod is needed there.
#
# What it demonstrates, and only this: the offline verifier accepts the
# untouched sample export and refuses a copy with one byte flipped inside a
# sealed record, naming the chain and Merkle-root failures. It does not
# demonstrate completeness of capture, enforcement, independent attestation,
# or resistance to a compromised signer — see
# https://aaes.ai/library/verification.html for what verification does not
# establish.
set -euo pipefail

cd "$(dirname "$0")"

case "$(uname -s)" in
  Darwin)                  OS=darwin ;;
  Linux)                   OS=linux ;;
  MINGW*|MSYS*|CYGWIN*)    OS=windows ;;
  *) echo "unsupported OS: $(uname -s)"; exit 2 ;;
esac
ARCH=$(uname -m | sed -e 's/^x86_64$/amd64/' -e 's/^aarch64$/arm64/')
AAESCTL="bin/aaesctl-${OS}-${ARCH}"
[ "$OS" = windows ] && AAESCTL="${AAESCTL}.exe"
[ -x "$AAESCTL" ] || { echo "no executable verifier at $AAESCTL (chmod +x it, or check your platform)"; exit 2; }
if command -v python3 >/dev/null 2>&1; then PY=python3
elif command -v python >/dev/null 2>&1; then PY=python
else echo "python3 is required for the byte flip"; exit 2; fi

# Work in a temporary directory so a pre-existing sample-export.tampered.jsonl
# is never overwritten or deleted.
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT
TAMPERED="$WORKDIR/sample-export.tampered.jsonl"

echo "=== 1. verify the untouched sample export (full output) ==="
"$AAESCTL" verify --export sample-export.jsonl --pubkey sample-pubkey.txt

echo
echo "=== 2. flip one byte inside the first sealed record of a COPY ==="
"$PY" - "$TAMPERED" <<'PY'
import sys
target = sys.argv[1]
data = bytearray(open("sample-export.jsonl", "rb").read())
marker = b'"record_hash":"'
i = data.find(marker)
if i < 0:
    raise SystemExit("record_hash marker not found; no demonstration performed")
j = i + len(marker)
if j >= len(data) or data[j] not in b"0123456789abcdef":
    raise SystemExit("unexpected record_hash format; no demonstration performed")
old = data[j]
data[j] = ord("b") if old == ord("a") else ord("a")
open(target, "wb").write(bytes(data))
print(f"flipped one byte at offset {j}: {chr(old)} -> {chr(data[j])} in the first entry record_hash")
PY

echo
echo "=== 3. verify the tampered copy (full output; must be refused) ==="
set +e
OUT=$("$AAESCTL" verify --export "$TAMPERED" --pubkey sample-pubkey.txt 2>&1)
RC=$?
set -e
printf '%s\n' "$OUT"

# Success means the documented integrity rejection, not merely any failure:
# exit 1 AND the chain and Merkle-root checks named as FAILED.
if [ "$RC" -ne 1 ] ||
   ! printf '%s\n' "$OUT" | grep -Eq '^chain:[[:space:]]+FAILED([[:space:]]|$)' ||
   ! printf '%s\n' "$OUT" | grep -Eq '^merkle root:[[:space:]]+FAILED([[:space:]]|$)'; then
  echo
  echo "TAMPER DEMO INCONCLUSIVE: expected integrity rejection was not observed. Do not rely on this build; contact hello@aaes.ai."
  exit 1
fi
echo
echo "TAMPER DEMO: the clean sample passed; the edited copy failed the chain and Merkle-root checks. This demonstrates detection of this edit only."
