#!/bin/sh

FAXFILTERS=./faxfilters
MIMETYPE=

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

while true; do
	case "$1" in
		--help)
			usage 0
			;;
		-m)
			shift
			FAXFILTERS="$1"
			shift
			;;
		--mime=*)
			MIMETYPE=${1#--mime=}
			shift
			;;
		-v)
			echo "Anytops v1.0: (c) 2001, Michael Goffioul <goffioul@imec.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"

function get_command() {
	while read mime command; do
		if [[ $MIMETYPE == $mime ]]; then
			echo $command
			break;
		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"

EXECCOMMAND=`echo $COMMAND | sed -e "s,%in,$INFILE," -e "s,%out,$OUTFILE,"`
eval "$EXECCOMMAND"
