#!/bin/bash
# uvgrep (UniVersal Grep), version 0.9el, 2016/07/03
# (c) Hans-Georg Esser, EasyLinux, hgesser@easylinux.de
# (c) überarbeitet von Peter Starfinger, info@die-starfingers.de
# uvgrep: grep txt, PDF and LibreOffice files
OPTERR=0
OPTIONS=""
ODTOPTIONS=""
params=()
recursive=false
case $LANGUAGE in
    de) opt_err="Ungültige Option"
	file_err="Datei nicht gefunden"
	ext1_err="Dateien vom Typ"
	ext2_err="können nicht durchsucht werden."
	;;
    en) opt_err="Invalid option"
	file_err="File not found"
	ext1_err="Files of the type"
	ext2_err="cannot be searched."
	;;
    es) opt_err="Opción no válida"
	file_err="Archivo no encontrado"
	ext1_err="Los archivos del tipo"
	ext2_err="no se pueden buscar."
	;;
    it) opt_err="Opzione non valida"
	file_err="File non trovato"
	ext1_err="I file del tipo"
	ext2_err="non possono essere cercati."
	;;
esac
export LANGUAGE=en
IFS=$'\n'
while getopts ":inr" option; do
  case $option in
    "?")
      echo $opt_err "-$OPTARG"
      exit 1;;
    "i")
      OPTIONS+=i
      ODTOPTIONS+=i;;
    "n")
      OPTIONS+=n;;
    "r")
      recursive=true;;
  esac
done
if [ "$OPTIONS" != "" ]; then OPTIONS="-$OPTIONS"; fi
if [ "$ODTOPTIONS" != "" ]; then ODTOPTIONS="-$ODTOPTIONS"; fi
shift $((OPTIND-1))
PATTERN=$1
shift
$recursive && params=($(find . -type f -name "$@")) || params=($@)
for file in ${params[*]}; do
  mimetype="$(file --mime-type "$file" | cut -d: -f2 | cut -d' ' -f2)"
  [ "$mimetype" = "cannot" ] && mime="text/unknown" || mime="$mimetype"
  case $mime in
    text* | *url)
      if [ -f $file ]; then
        grep -H -E --color $OPTIONS $PATTERN $file
      else
        echo $file: $file_err >&2
      fi;;
    *pdf)
      if [ -f $file ]; then
        pdfgrep -H $OPTIONS -e $PATTERN $file
      else
        echo $file: $file_err >&2
      fi;;
    *opendocument*)
      unzip -caq $file content.xml | xmllint --format - \
        | sed -e 's/ *//' \
        | grep $ODTOPTIONS -H -E --color $PATTERN \
        | sed -e "s|^(standard input)|$file|" ;;
    *)
      [ "$mime" != "inode/directory" ] && ! $recursive && echo $file: $ext1_err "\"$mime\"" $ext2_err >&2;;
  esac
done
