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

product_dir="$(cd "$(dirname "$0")" && pwd)"
fixture="$(mktemp -d)"
trap 'rm -rf "$fixture"' EXIT

mkdir -p "$fixture/src" "$fixture/node_modules"
printf '%s\n' 'AWS_KEY="AKIAABCDEFGHIJKLMNOP"' > "$fixture/src/config.py"
printf '%s\n' 'password="s3cure-Random-Value-991"' >> "$fixture/src/config.py"
printf '%s\n' 'token="example_placeholder_token"' >> "$fixture/src/config.py"
printf '%s\n' 'AKIAZZZZZZZZZZZZZZZZ' > "$fixture/node_modules/ignored.js"
printf '\0binary AKIAQQQQQQQQQQQQQQQQ' > "$fixture/binary.dat"

set +e
"$product_dir/leak-audit.py" "$fixture" --fail-on-findings > "$fixture/report.md"
status=$?
set -e
test "$status" -eq 2
grep -q 'aws-access-key' "$fixture/report.md"
grep -q 'assigned-secret' "$fixture/report.md"
grep -q 'AKIA…MNOP' "$fixture/report.md"
! grep -q 'AKIAABCDEFGHIJKLMNOP' "$fixture/report.md"
! grep -q 'placeholder' "$fixture/report.md"
! grep -q 'ignored.js' "$fixture/report.md"
grep -q 'Findings: \*\*2\*\*' "$fixture/report.md"

empty="$(mktemp -d)"
trap 'rm -rf "$fixture" "$empty"' EXIT
printf '%s\n' 'print("clean")' > "$empty/app.py"
"$product_dir/leak-audit.py" "$empty" --fail-on-findings >/dev/null

echo "leak-audit tests passed"
