#!/bin/sh
#< grep for first match of searchstring, then exit 
# can take STDIN from pipe, redirection or file
# KW 20/10/04

thiscmd=`basename $0`

if [ "$#" -lt "1" -o "$#" -gt "3" ]; then
   echo "USAGE: $thiscmd [-n] searchterm [file]" && exit 1
fi

grep_n=""
case $1 in
  "-n" ) grep_n="-n"; shift ;;
  *   ) ;;  #do nothing
esac

searchterm="$1"
file_to_search="$2"

if [ -z "$2" ]; then
  # assume pipe mode
  while read line; do
     echo "$line" | grep $grep_n "$1" 
     if [ "$?" -eq "0" ]; then
  		exit 0;
     fi 
  done
  exit 2		# searchterm not found
fi

if [ ! -e "$2" ]; then
  echo "Error: ${2}: File not found"
  exit 1
fi

while read line; do 
  echo "$line" | grep $grep_n "$1" 
  if [ "$?" -eq "0" ]; then
    exit 0;
  fi 
done < ${2}

exit 2  # searchterm not found