#!/bin/sh
SCRIPT=`basename $0`
case "$SCRIPT" in
    ("kleiner")
        MAXWIDTH=800
        ;;
    ("kleines")
        MAXWIDTH=1280
        ;;
    ("klein2")
        MAXWIDTH=1440
        # x1080
        ;;
    ("klein")
        MAXWIDTH=1920
        # x1080
        ;;
    ("klein_gross")
        MAXWIDTH=3936
        # x2624
        ;;
    (*)
        echo "$SCRIPT is unknown"
        exit -1
        ;;
esac

mkdir -p $SCRIPT
for i in `find . -maxdepth 1 \( -type f -o -type l \) -iname \*.jpg | sort` ; do
    width=`identify -verbose info "$i" 2>/dev/null | grep Geometry | sed 's/^.*Geometry:[[:space:]]*\([0-9]\+\)x.*/\1/'`
    target=$SCRIPT/`basename "$i" | tr [A-Z] [a-z]`
    if [ $width -gt $MAXWIDTH ] ; then
	# -quality 65 ist manchmal nicht schön
        convert "$i" -quality 75 -geometry ${MAXWIDTH}x${MAXWIDTH} "$target"
        touch -r "$i" "$target"
    else
        height=`identify -verbose info "$i" 2>/dev/null | grep Geometry | sed 's/^.*Geometry:[[:space:]]*[0-9]\+x\([0-9]\+\).*/\1/'`
        if [ $height -gt $MAXWIDTH ] ; then
            # -quality 65 ist manchmal nicht schön
            convert "$i" -quality 75 -geometry ${MAXWIDTH}x${MAXWIDTH} "$target"
            touch -r "$i" "$target"
        else
            ln -s ../"$i" "$target"
        fi
    fi
done
