#!/bin/bash
set -euo pipefail

WORKDIR="/tmp/pillow_psd_oob_variant"
LOGDIR="/data/pruva/runs/19d27887-3653-4a01-ad54-44532ad3744c/logs"
LOGFILE="$LOGDIR/variant_evidence.log"

rm -rf "$WORKDIR"
mkdir -p "$WORKDIR" "$LOGDIR"

python -m venv "$WORKDIR/venv"
source "$WORKDIR/venv/bin/activate"

pip install --upgrade pip >/dev/null
pip install pillow==12.1.0 >/dev/null

echo "Using Python: $(python --version)" | tee "$LOGFILE"

git clone https://github.com/python-pillow/Pillow.git "$WORKDIR/Pillow" >/dev/null
cd "$WORKDIR/Pillow"
# Commit that added crafted PSD regression samples for this issue
GIT_COMMIT="54ba4db542ad3c7b918812a4e2d69c27735a3199"
git fetch --depth 1 origin "$GIT_COMMIT" >/dev/null
git checkout -q FETCH_HEAD

PSD_DIR="$WORKDIR/Pillow/Tests/images"
ls -l "$PSD_DIR"/psd-oob-write*.psd | tee -a "$LOGFILE"

python - <<'PY' | tee -a "$LOGFILE"
from PIL import Image
import glob
import os

psd_files = sorted(glob.glob(os.path.join("/tmp/pillow_psd_oob_variant/Pillow/Tests/images", "psd-oob-write*.psd")))
print("Using Pillow version:", Image.__version__)
for path in psd_files:
    print("\nOpening", path)
    with Image.open(path) as im:
        print("Format:", im.format, "frames:", im.n_frames, "size:", im.size)
        im.seek(im.n_frames)
        try:
            im.load()
            print("Loaded without exception (potentially unsafe)")
        except Exception as exc:
            print("Exception:", type(exc).__name__, exc)
PY
