#!/bin/sh

FAXFILTERS=./faxfilters
MIMETYPE=
PAGE="letter"

usage() {
	echo "Usage: anytops [-m <filters>] [--mime=<mime-type>] [-p <page>] [--help] <infile> <outfile>"
	exit $1
}

while true; do
	case "$1" in
		--help)
			usage 0
			;;
		-m)
			shift
			FAXFILTERS="$1"
			shift
			;;
		--mime=*)
			MIMETYPE=${1#--mime=}
			shift
			;;
		-p)
			shift
			PAGE="$1"
			shift
			;;
		-v)
			echo "Anytops v1.0: (c) 2001, Michael Goffioul <kdeprint@swing.be>";
			echo "Small script to convert any file type into PS. Part of kdeprintfax."
			exit 0
			;;
		*)
			break;
			;;
	esac
done

INFILE=$1
OUTFILE=$2

if [ -z "$INFILE" -o -z "$OUTFILE" -o ! -f "$INFILE" ]; then
	usage 1;
fi

if [ -z "$MIMETYPE" ]; then
	MAGIC=$KDEDIR
	if [ -z "$MAGIC" ]; then
		MAGIC=/usr
	fi
	MAGIC=$MAGIC/share/mimelnk/magic

	if [ ! -f "$MAGIC" ]; then
		echo "KDE magic file not found. Check your installation."
		exit 1;
	fi

	MIMETYPE=`file -b -m $MAGIC "$INFILE" 2> /dev/null`
	MIMETYPE=${MIMETYPE%%;*}
fi

echo "Mime type: $MIMETYPE"
MIMETYPE_BASE=`echo $MIMETYPE | cut -f 1 -d "/"`
MIMETYPE_TYPE=`echo $MIMETYPE | cut -f 2- -d "/"`

get_command() {
	while read mime command; do
		mimebase=`echo $mime | cut -f 1 -d "/"`
		mimefile=`echo $mime | cut -f 2- -d "/"`
		if test "$mimebase" = "$MIMETYPE_BASE" || test "$mimebase" = "*"; then
			if test "$mimefile" = "$MIMETYPE_TYPE" || test "$mimefile" = "*"; then
				echo $command
				break;
			fi
		fi
#		PATTERN=`echo $MIMETYPE | grep $mime`
#		if [ "$PATTERN" = "$MIMETYPE" ]; then
#			echo $command
#			break;
#		fi
	done
}

COMMAND=`cat $FAXFILTERS | get_command`

if [ -z "$COMMAND" ]; then
	echo "$MIMETYPE: file type not handled"
	exit 1;
fi

echo "Command: $COMMAND"

PAGEUP="`echo $PAGE | cut -c 1 | tr [:lower:] [:upper:]``echo $PAGE | cut -c 2-`"
EXECCOMMAND=`echo $COMMAND | sed -e "s,%in,\"$INFILE\"," -e "s,%out,\"$OUTFILE\"," -e "s,%psl,$PAGE," -e "s,%psu,$PAGEUP,"`
eval "$EXECCOMMAND"
