#!/bin/sh

page_width=2480
page_height=3508
images_per_page=4

rm -f output.pdf
tmp_imgs=""

for f in out/*_GD.*; do
    [ -f "$f" ] || continue
    tmp="tmp_$(basename "$f")"
    convert "$f" -resize "${page_width}x$((page_height / images_per_page))>" "$tmp"
    tmp_imgs="$tmp_imgs $tmp"
done

# Diviser en pages de 4 images
i=1
for img in $tmp_imgs; do
    set -- $img "$@"
    if [ $((i % images_per_page)) -eq 0 ]; then
        montage "$@" -tile 1x$images_per_page -geometry +0+20 -background white "page_$((i / images_per_page)).pdf"
        set --
    fi
    i=$((i+1))
done

# Fusionner toutes les pages
convert page_*.pdf output.pdf

# Nettoyage
rm tmp_* page_*.pdf