#!/bin/bash
# This script does a basic open of an image with gimp. It was intended to
# track down a potential address space exhaustion bug
# https://bugzilla.kernel.org/show_bug.cgi?id=67651
#
P=gimp-simple-bench
DEFAULT_VERSION=0
. $SHELLPACK_INCLUDE/common.sh

install-depends xorg-x11-server xinit gimp

# Basic argument parser
TASKSET_SERVER=
TASKSET_CLIENT=

while [ "$1" != "" ]; do
	case "$1" in
	-v)
		VERSION=$2
		shift 2
		;;
	--install-only)
		INSTALL_ONLY=yes
		shift
		;;
	--install-force)
		INSTALL_FORCE=yes
		shift
		;;
	-i)
		GIMP_SIMPLE_IMAGE_LOCATION=$2
		shift 2
		;;
	*)
		echo Unrecognised option: $1
		shift
	esac
done
if [ "$TASKSET_SERVER" != "" ]; then
	echo TASKSET_SERVER: $TASKSET_SERVER
	echo TASKSET_CLIENT: $TASKSET_CLIENT
fi
if [ -z "$VERSION" ]; then
	VERSION=$DEFAULT_VERSION
fi

if [ "$SHELLPACK_TEMP" = "" ]; then
	die SHELLPACK_TEMP not refined
fi

GIMP_DATA_DIR=$HOME/.gimp-2.8

# Create directories gimp expects
for NAME in brushes dynamics patterns gradients palettes; do
	mkdir $GIMP_DATA_DIR/$NAME
done

# Write the gimp script
cd $SHELLPACK_TEMP || die Failed to cd to $SHELLPACK_TEMP
mkdir -p $GIMP_DATA_DIR/scripts/ || die Failed to create gimp script directory
echo "(define (mmtests-open-image filename)
  (let* 
    (
      (image    (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
      (drawable (car (gimp-image-get-active-layer image)))
      (gimp-image-delete image)
    )
  )
)" > $GIMP_DATA_DIR/scripts/mmtests-open-image.scm

FILENAME=`basename $GIMP_SIMPLE_IMAGE_LOCATION`
wget $GIMP_SIMPLE_IMAGE_LOCATION -O $FILENAME || die Failed to download image from $GIMP_SIMPLE_IMAGE_LOCATION

TIME_CMD=`which time`
if [ "$TIME_CMD" = "" ]; then
        TIMEFORMAT="%2Uuser %2Ssystem %Relapsed %P%%CPU"
        TIME_CMD="time"
fi

# Build a wrapper script to launch gimp
cat > gimp-launch.sh << EOF
/usr/bin/gimp -i -b "(mmtests-open-image \"$FILENAME\")" -b "(gimp-quit 0)" > $LOGDIR_RESULTS/gimp-out.1 2>&1
echo \$? > gimp-exit-code
EOF
chmod u+x gimp-launch.sh

$TIME_CMD xinit ./gimp-launch.sh 2> $LOGDIR_RESULTS/time.1
RETVAL=`cat gimp-exit-code`
rm $FILENAME
cd /

if [ "$RETVAL" != "0" ]; then
	die gimp exited with error
fi
grep -q "batch command executed successfully" $LOGDIR_RESULTS/gimp-out.1
if [ $? -ne 0 ]; then
	die gimp output does not match expectations
fi

exit $SHELLPACK_SUCCESS
#### Description Simple gimp manipulation
#### Details gimp-simple-bench 8
