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

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

SANDBOX="$ROOT_DIR/sandbox/rho-repo-doctor"
REPO="$SANDBOX/repo"
USER1_ID="rho://id/github/rho-owner"
USER2_ID="rho://id/github/rho-collab"
REQUEST_PATH="rho/messages/inbox/rho-owner/request.yaml.rhoenc"

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

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

./rho repo init \
  --root "$REPO" \
  --repo-id rho://repo/local/doctor \
  --owner "$USER1_ID" >/dev/null

RHO_HOME="$SANDBOX/user1-rho-home" ./rho id init \
  --github rho-owner \
  --display-name "Rho Owner" \
  --generate-ssh-key >/dev/null
RHO_HOME="$SANDBOX/user2-rho-home" ./rho id init \
  --github rho-collab \
  --display-name "Rho Collaborator" \
  --generate-ssh-key >/dev/null

RHO_HOME="$SANDBOX/user1-rho-home" ./rho id export \
  --identity "$USER1_ID" \
  --out "$REPO/rho/participants/rho-owner.yaml" >/dev/null
RHO_HOME="$SANDBOX/user2-rho-home" ./rho id export \
  --identity "$USER2_ID" \
  --out "$REPO/rho/participants/rho-collab.yaml" >/dev/null

cat > "$REPO/rho/membership.yaml" <<EOF
version: 1
members:
  - identity: $USER1_ID
    role: owner
  - identity: $USER2_ID
    role: collaborator
EOF

cat > "$REPO/rho/policy/permissions.yaml" <<EOF
version: 1
permissions:
  - id: owner_inbox
    pattern: rho/messages/inbox/rho-owner/**
    write:
      allowed:
        - members
    read:
      encrypted_to:
        - $USER1_ID
EOF
printf "rho/messages/inbox/rho-owner/** filter=rho-crypt diff=rho-crypt\n" >> "$REPO/.gitattributes"

RHO_HOME="$SANDBOX/user2-rho-home" ./rho id import \
  "$REPO/rho/participants/rho-owner.yaml" >/dev/null
mkdir -p "$REPO/rho/messages/inbox/rho-owner"
cat > "$SANDBOX/request.yaml" <<EOF
version: 1
request:
  note: private request for owner
EOF
RHO_HOME="$SANDBOX/user2-rho-home" ./rho crypto seal \
  "$SANDBOX/request.yaml" \
  --recipient "$USER1_ID" \
  --out "$REPO/$REQUEST_PATH" >/dev/null

git -C "$REPO" add .gitattributes rho
RHO_HOME="$SANDBOX/user1-rho-home" ./rho repo doctor --root "$REPO" >"$SANDBOX/doctor-pass.txt"
grep -q "rho repo doctor passed" "$SANDBOX/doctor-pass.txt"

cat > "$REPO/rho/messages/inbox/rho-owner/plaintext.yaml" <<EOF
version: 1
request:
  note: this should have been encrypted
EOF
if RHO_HOME="$SANDBOX/user1-rho-home" ./rho repo doctor --root "$REPO" >"$SANDBOX/doctor-fail-stdout.txt" 2>"$SANDBOX/doctor-fail-stderr.txt"; then
  echo "doctor allowed plaintext protected path" >&2
  exit 1
fi
grep -q "private-read file is not encrypted: rho/messages/inbox/rho-owner/plaintext.yaml" "$SANDBOX/doctor-fail-stderr.txt"

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