#!/bin/bash

# This file is part of Marionnet
# Copyright (C) 2013  Jean-Vincent Loddo
# Copyright (C) 2013  Université Paris 13
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Poor-man's (and quite ugly) versions of zgrep zegrep zfgrep zless zdiff zcmp zhead ztail.
# Limitations: options with argument(s) are not supported (for instance diff -C N) except
# when the argument doesn't correspond to an existing file.

# Dependencies: zcat (or cat & gunzip), mktemp, rm

# [OPTION].. PATTERN [FILE]..
function grep_like_call {
 local PROGRAM="$1"; shift;
 local OPTIONS
 while [[ "-${1#-}" = "${1}" ]]; do OPTIONS+="${1} "; shift; done
 local PATTERN="$1"; shift;
 local ZCAT
 if ZCAT=$(type -P zcat); then
   $ZCAT "$@" | $PROGRAM $OPTIONS "$PATTERN"
 else
   cat "$@" | gunzip -c | $PROGRAM $OPTIONS "$PATTERN"
 fi
}

# [OPTION].. [FILE]..
function less_like_call {
 local PROGRAM="$1"; shift;
 local OPTIONS
 while [[ "-${1#-}" = "${1}" ]]; do OPTIONS+="${1} "; shift; done
 # Ugly but why not: try to capture arguments that aren't existing files:
 while [[ ! -e "${1}" ]]; do OPTIONS+="${1} "; shift; done
 local ZCAT
 if ZCAT=$(type -P zcat); then
   $ZCAT "$@" | $PROGRAM $OPTIONS
 else
   cat "$@" | gunzip -c | $PROGRAM $OPTIONS
 fi
}

# [OPTION].. FILE1 FILE2
function diff_like_call {
 local PROGRAM="$1"; shift;
 local OPTIONS
 while [[ "-${1#-}" = "${1}" ]]; do OPTIONS+="${1} "; shift; done
 # Ugly but why not: try to capture arguments that aren't existing files:
 while [[ ! -e "${1}" ]]; do OPTIONS+="${1} "; shift; done
 [[ $# -eq 2 ]] || return 1
 local FILE1="$1";
 local FILE2="$2";
 local TMPFILE1=$(mktemp /tmp/$(basename "$FILE1").XXXXXX)
 local TMPFILE2=$(mktemp /tmp/$(basename "$FILE2").XXXXXX)
 local ZCAT
 if ZCAT=$(type -P zcat); then
   $ZCAT "$FILE1" > "$TMPFILE1"
   $ZCAT "$FILE2" > "$TMPFILE2"
 else
   cat "$FILE1" | gunzip -c > "$TMPFILE1"
   cat "$FILE2" | gunzip -c > "$TMPFILE2"
 fi
 $PROGRAM "$TMPFILE1" "$TMPFILE2"
 rm -f "$TMPFILE1" "$TMPFILE2"
}

# Main
PROGRAM=$(basename $0)
case $PROGRAM in
 zgrep|zegrep|zfgrep) grep_like_call ${PROGRAM#z} "$@";;
   zless|zhead|ztail) less_like_call ${PROGRAM#z} "$@";;
          zdiff|zcmp) diff_like_call ${PROGRAM#z} "$@";;
esac
