#!/bin/bash
set -euo pipefail

WORKDIR="/tmp/pillow_psd_oob"
rm -rf "$WORKDIR"
mkdir -p "$WORKDIR"

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

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

# Get crafted PSDs introduced in the fix commit
if [ ! -d "$WORKDIR/Pillow" ]; then
  git clone https://github.com/python-pillow/Pillow.git "$WORKDIR/Pillow" >/dev/null
fi

# Fetch the commit that added the crafted PSDs
cd "$WORKDIR/Pillow"
git fetch --depth 1 origin 54ba4db542ad3c7b918812a4e2d69c27735a3199 >/dev/null

git checkout -q FETCH_HEAD

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

python - <<'PY'
from PIL import Image
import glob
import os

psd_files = sorted(glob.glob(os.path.join("/tmp/pillow_psd_oob/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
