#!/bin/bash
# BAM's magic-filter
# (C) Brian McCauley (B.A.McCauley@bham.ac.uk) 1993

# lpd does not necessarily have a sensible PATH environment variable
PATH=$PATH:/usr/bin:/bin:/usr/local/bin

# This same file may be linked to several names to service different
# printers and/or behave differently for different lpr switches. 
basename=${0##*/}

# Find out if my input's piped - if so I need a tmp file.
if rewind-stdin ; then
  tmpfile=""
else
  # Get an unused temp file name (this script is re-entrant)
  while tmpfile=/tmp/$basename.$$.$RANDOM; test -e $tmpfile; do :; done
fi

if [ -z "$tmpfile" ] ; then
  magic=`file -`
else 
  # Save the 1st kB of the file and hope this is enough for file to
  # recognise the type. (Don't save the whole thing in case it's BIG).
  dd bs=1 count=1024 of=$tmpfile 2>/dev/null
  magic=`file $tmpfile`
fi

magic=${magic#*:\ }
 
filter=""
prefilter=""
nopipe=0

# config is a sparate file to allow for new releases of this file
source ${0%/*}/config

if [ -n "$prefilter" ]; then
  if [ -z "$tmpfile" ]; then
    rewind-stdin
    eval $prefilter | $0 $*
  else
    ( cat $tmpfile; rm $tmpfile; cat ) | \
    eval $prefilter | $0 $*
  fi
  exit
fi
  
if [ -z "$filter" ] ; then
  echo $0: "Can't handle $magic" >&2
else
  if [ -z "$tmpfile" ]; then
    rewind-stdin
    exec $filter $*
  else
    # If this filter needs a rewindable STDIN then the whole thing
    # must go in the tmpfile
    if [ "$nopipe" = 1 ]; then 
      cat >>$tmpfile
      $filter $* <$tmpfile
    else
      ( cat $tmpfile; rm $tmpfile; cat ) | $filter $*
      exit
    fi
  fi
fi

if [ -n "$tmpfile" ] ; then
  rm $tmpfile
fi



