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

ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT_DIR"

SANDBOX="$ROOT_DIR/sandbox/rho-audit-encryption"
REPO="$SANDBOX/repo"
OWNER_HOME="$SANDBOX/owner-rho-home"
OWNER_ID="rho://id/github/rho-owner"
PROTECTED_PATH="rho/messages/inbox/rho-owner/result.yaml"
BYPASS_PATH="rho/messages/inbox/rho-owner/bypass.yaml"

rm -rf "$SANDBOX"
mkdir -p "$REPO"

git -C "$REPO" init >/dev/null
git -C "$REPO" config user.name "Rho Audit Test"
git -C "$REPO" config user.email "audit@example.test"
git -C "$REPO" config commit.gpgsign false

RHO_HOME="$OWNER_HOME" ./rho id init \
  --github rho-owner \
  --display-name "Rho Owner" \
  --generate-ssh-key >/dev/null

./rho repo init \
  --root "$REPO" \
  --repo-id rho://repo/local/audit-encryption \
  --owner "$OWNER_ID" >/dev/null
RHO_HOME="$OWNER_HOME" ./rho id export \
  --identity "$OWNER_ID" \
  --out "$REPO/rho/participants/rho-owner.yaml" >/dev/null

RHO_HOME="$OWNER_HOME" ./rho repo protect-path \
  "rho/messages/inbox/rho-owner/**" \
  --root "$REPO" \
  --rho-bin "$ROOT_DIR/rho" \
  --recipient "$OWNER_ID" >/dev/null

mkdir -p "$REPO/$(dirname "$PROTECTED_PATH")"
cat > "$REPO/$PROTECTED_PATH" <<EOF
version: 1
result:
  total: 1113.03
EOF

RHO_HOME="$OWNER_HOME" git -C "$REPO" add .gitattributes .gitignore rho rho.yaml
git -C "$REPO" commit -m "Publish encrypted result" >/dev/null

RHO_HOME="$OWNER_HOME" ./rho repo audit-encryption \
  --root "$REPO" \
  > "$SANDBOX/audit-pass.txt"
grep -q "rho encryption audit passed" "$SANDBOX/audit-pass.txt"
grep -q "index: encrypted recipient envelope" "$SANDBOX/audit-pass.txt"
grep -q "HEAD: encrypted recipient envelope" "$SANDBOX/audit-pass.txt"

cat > "$SANDBOX/plaintext-bypass.yaml" <<EOF
version: 1
result:
  leaked: plaintext
EOF
PLAINTEXT_BLOB="$(git -C "$REPO" hash-object -w "$SANDBOX/plaintext-bypass.yaml")"
git -C "$REPO" update-index --add --cacheinfo "100644,$PLAINTEXT_BLOB,$BYPASS_PATH"

if RHO_HOME="$OWNER_HOME" ./rho repo audit-encryption \
  --root "$REPO" \
  > "$SANDBOX/audit-index-fail-stdout.txt" \
  2> "$SANDBOX/audit-index-fail-stderr.txt"; then
  echo "audit-encryption allowed plaintext protected index blob" >&2
  exit 1
fi
grep -q "index blob is not encrypted: $BYPASS_PATH" "$SANDBOX/audit-index-fail-stderr.txt"

git -C "$REPO" -c core.hooksPath=/dev/null commit -m "Bypass encryption" >/dev/null
if RHO_HOME="$OWNER_HOME" ./rho repo audit-encryption \
  --root "$REPO" \
  > "$SANDBOX/audit-head-fail-stdout.txt" \
  2> "$SANDBOX/audit-head-fail-stderr.txt"; then
  echo "audit-encryption allowed plaintext protected HEAD blob" >&2
  exit 1
fi
grep -q "HEAD blob is not encrypted: $BYPASS_PATH" "$SANDBOX/audit-head-fail-stderr.txt"

echo "inspect sandbox: $SANDBOX"
find "$SANDBOX" \
  -path "*/.git" -prune -o \
  -maxdepth 7 -type f -print | sort
echo "rho audit encryption e2e passed"
