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

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

SANDBOX="$ROOT_DIR/sandbox/rho-safe-tar-extract"

rm -rf "$SANDBOX"
mkdir -p "$SANDBOX/good-src/rho/requests" "$SANDBOX/good-out"

cat > "$SANDBOX/good-src/rho/requests/req-safe.yaml" <<EOF
version: 1
request:
  id: req-safe
EOF
tar --format ustar -cf "$SANDBOX/good.tar" -C "$SANDBOX/good-src" rho
./rho crypto extract-tar "$SANDBOX/good.tar" --out-dir "$SANDBOX/good-out" >/dev/null
cmp "$SANDBOX/good-src/rho/requests/req-safe.yaml" "$SANDBOX/good-out/rho/requests/req-safe.yaml"

mkdir -p "$SANDBOX/bad-src"
ln -s /etc/passwd "$SANDBOX/bad-src/passwd-link"
tar --format ustar -cf "$SANDBOX/symlink.tar" -C "$SANDBOX/bad-src" passwd-link
if ./rho crypto extract-tar "$SANDBOX/symlink.tar" --out-dir "$SANDBOX/bad-out" >"$SANDBOX/bad-stdout.txt" 2>"$SANDBOX/bad-stderr.txt"; then
  echo "safe tar extractor allowed symlink entry" >&2
  exit 1
fi
grep -q "symlink rejected" "$SANDBOX/bad-stderr.txt"

echo "inspect sandbox: $SANDBOX"
find "$SANDBOX" \
  -maxdepth 5 -type f -print | sort
echo "rho safe tar extract e2e passed"
