#! /bin/bash

set -e

fu="
    (define (make-thumb fin fout size)
        (let*
            (
                (image      (car (gimp-file-load RUN-NONINTERACTIVE fin fin)))
                (drawable   (car (gimp-image-active-drawable image)))
                (cur-width  (car (gimp-image-width image)))
                (cur-height (car (gimp-image-height image)))
                (ratio      (min (/ size cur-width) (/ size cur-height)))
                (width      (* ratio cur-width))
                (height     (* ratio cur-height))
            )

            (gimp-image-scale image width height)
            (gimp-file-save RUN-NONINTERACTIVE image drawable fout fout)
            (gimp-image-delete image)
        )
    )

    (make-thumb \"$1\" \"$2\" $3 $3)
    (gimp-quit 0)
"

# GIMP doesn't clean its tmpdir after exit [0], which causes gnome-desktop's
# bwrap-based thumbnailer to leave its workspace hanging around in /tmp. Work
# around this by forcing GIMP to write to a new tmp directory, then clearing it
# on exit.
#
# [0] https://gitlab.gnome.org/GNOME/gimp/-/merge_requests/314
export TMPDIR=$(mktemp -d)
trap "rm -r $TMPDIR" EXIT

gimp-console \
    --no-interface \
    --batch "$fu" \
    --batch "(gimp-quit 0)" # In case of script failures, always exit
