#!/bin/bash

ECPATH=$(type -p voxren)

ECPATH=${ECPATH%/voxren}
ECPATH=${ECPATH%/bin}
JPGCONFPATH=${ECPATH}/share/eccet/config/modules/save/GENPPM

echo "Install Path is $ECPATH"
echo

#
# Do some preliminary checks about available programs.
#


PROG=$(type -p cjpeg)
[ "$PROG" == "" ] && \
	{ echo "cjpeg is required for writing JPEG output."; \
	  echo "Please install the libjpeg-progs package."; \
	  exit 1; }
[ -x $PROG ] || \
	{ echo "cjpeg is there but not executable."; \
	  echo "Please install the libjpeg-progs package correctly."; \
	  exit 1; }

if [ $# == 0 ] ; then
	echo "Usage: $0 [-d] -q quality -s smoothing"
	echo "       $0 [-d] -a (delete all)"
	echo "Sets up or deletes quality profiles for use by the Eccet "
	echo "JPEG save module."
	echo "See man ${0##*/} for details."
	exit 1
fi

DO_DELETE=0
QUALITY=""
SMOOTHING=""

while getopts "daq:s:" OPTCHAR; do
	case "$OPTCHAR" in
		"d")
			DO_DELETE=1
		;;
		"a")
			if [ "$DO_DELETE" == "1" ] ; then
				DO_DELETE=2
			else
				echo "-a only valid after -d."
				exit 1;
			fi
		;;
		"q")
			QUALITY=$OPTARG
			QUALITY=$((QUALITY+0))
		;;
		"s")
			SMOOTHING=$OPTARG
			SMOOTHING=$((SMOOTHING+0))
		;;
	esac
done

function ask_delete() {
	cd $JPGCONFPATH
	BINDINGS=$(ls $1 2>/dev/null | sed -ne "s/\.test\$//p")
	if [ "$BINDINGS" == "" ] ; then
		echo "No profiles found. Aborting."
		exit 1
	fi
	echo "The following JPEG quality profiles will be deleted:"
	echo "$BINDINGS"
	echo
	echo "Do you want to delete these profiles? (yes or no)"
	while read a; do
		if [ "$a" == "yes" ]; then
			break;
		elif [ "$a" == "no" ] ;  then
			echo "O.k. - aborting."
			exit 1;
		else
			echo "Please answer yes or no."
		fi
	done
	echo "O.k. - deleting."
	for a in $BINDINGS; do
		rm -f $a $a.test
	done
	exit
}

if [ "$DO_DELETE" == "2" ] ; then
	ask_delete "JPEG_Q*_S*.test"
fi

if [ "$QUALITY" == "" ] ; then
	echo "Quality must be given."
	exit 1
fi

ZFQUALITY=$(printf %03d $QUALITY)

if [ "$SMOOTHING" == "" ] ; then
	echo "Smoothing must be given."
	exit 1
fi

ZFSMOOTHING=$(printf %03d $SMOOTHING)

PROFILENAME="JPEG_Q${ZFQUALITY}_S${ZFSMOOTHING}"

if [ "$DO_DELETE" == "1" ] ; then
	ask_delete "$PROFILENAME.test"
fi


echo "You requested to add a Eccet JPEG profile called $PROFILENAME."

if [ -f $JPGCONFPATH/$PROFILENAME ] ; then
	echo "Config file exists. Unchanged."
	echo "Please delete it first, if you want to update that."
else
	cat >$JPGCONFPATH/$PROFILENAME <<EOF
# Quality $QUALITY - Smoothing $SMOOTHING
|cjpeg -quality $QUALITY -smooth $SMOOTHING >%s/%s_%08d.jpg
EOF
	cat >$JPGCONFPATH/$PROFILENAME.test <<EOF
#!/bin/bash
PROG=\$(type -p cjpeg)
[ "\$PROG" == "" ] && exit 1
[ -x \$PROG ] || exit 1
EOF
	chmod a+x $JPGCONFPATH/$PROFILENAME.test
fi
