#!/bin/bash
#
# $Id$

export GPGOPTS="--use-agent"

SEARCHTEXT="$1"
if [ -z "$SEARCHTEXT" ] ; then
  echo "FATAL: No search text specified to grep for."
  exit 1
fi
shift

if [ -z "$1" ] ; then
  echo "FATAL: No file specified to grep."
  exit 1
fi

for ORIGINAL in $* ; do
  #echo "Checking $ORIGINAL"
  if [ ! -e "$ORIGINAL" ] ; then
    echo "FATAL: No such file: $ORIGINAL"
    exit 2
  fi
done

HITLIST=""

for ORIGINAL in $* ; do
  if [ -f "$ORIGINAL" ] ; then
    test -n "$2" && echo "BEGIN $ORIGINAL"
    export GPGNAME=$(echo "$ORIGINAL" |egrep "\.(gpg|pgp)$" 2>/dev/null)
    CURHIT=""
    if [ -n "$GPGNAME" ] ; then
      #echo "DEBUG: gpg $GPGOPTS --decrypt --output - $ORIGINAL"
      test -f /tmp/sircat_$$.log && rm -f /tmp/sircat_$$.log 
      test -f /tmp/sircat_$$.err && rm -f /tmp/sircat_$$.err 
      #echo "gpg $GPGOPTS --decrypt --status-file /tmp/sircat_$$.log --logger-file /tmp/sircat_$$.log --attribute-file /tmp/sircat_$$.log $ORIGINAL 2>/tmp/sircat_$$.err |egrep -i $SEARCHTEXT"
      export PRC=-1
      CURHIT=$(gpg $GPGOPTS --decrypt --status-file /tmp/sircat_$$.log --logger-file /tmp/sircat_$$.log --attribute-file /tmp/sircat_$$.log $ORIGINAL 2>/tmp/sircat_$$.err |egrep -i $SEARCHTEXT ; exit ${PIPESTATUS[0]})
      #PRC=${PIPESTATUS[0]}
      PRC=$?
      if [ ! "$PRC" = "0" ] ; then
        echo "WARNING: gpg return code was bad ($PRC not 9), you might want to   cat /tmp/sircat_$$.err"
        # exit 1
      else
        rm /tmp/sircat_$$.log /tmp/sircat_$$.err
      fi
    else
      if [ -x /usr/bin/strings ] ; then
        /usr/bin/strings $ORIGINAL
      else
        CURHIT=$(cat $ORIGINAL |egrep -i $SEARCHTEXT)
      fi
    fi
    if [ ! -z "$CURHIT" ] ; then
      #echo "DEBUG: CurHit in $ORIGINAL: $CURHIT"
      if [ -n "$2" ] ; then
       HITLIST=$( echo "$HITLIST" ; echo "Hit(s) in $ORIGINAL" ; echo "$CURHIT" )
      else
       HITLIST=$( echo "$HITLIST" ; echo "$CURHIT" )
      fi
     #echo "DEBUG: New HitList: $HITLIST"
    fi
    test -n "$2" && echo "END $ORIGINAL"
  else
    echo "Ignoring non-file: $ORIGINAL"
  fi
done

#echo "HitList:"
echo "$HITLIST"

