#!/bin/bash
#
# $Id$

export GPGOPTS="--use-agent"

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

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

for ORIGINAL in $* ; do
  #test -n "$2" && echo "BEGIN $ORIGINAL"
  export GPGNAME=$(echo "$ORIGINAL" |egrep "\.(gpg|pgp)$" 2>/dev/null)
  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 "DEBUG: gpg $GPGOPTS --decrypt --status-file /tmp/sircat_$$.log --logger-file /tmp/sircat_$$.log --attribute-file /tmp/sircat_$$.log --output - $ORIGINAL"
    gpg $GPGOPTS --decrypt --status-file /tmp/sircat_$$.log --logger-file /tmp/sircat_$$.log --attribute-file /tmp/sircat_$$.log --output - $ORIGINAL 2>/tmp/sircat_$$.err 
    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
      echo "Assuming yubikey/gpg-agent hickup and continuing anyway"
    else
      rm -f /tmp/sircat_$$.log  /tmp/sircat_$$.err
    fi
  else
    if [ -x /usr/bin/strings ] ; then
      /usr/bin/strings $ORIGINAL
    else
      cat $ORIGINAL
    fi
  fi
  #test -n "$2" && echo "END $ORIGINAL"
done

