#!/bin/sh -e

[ -z "${LESSPIPE_DISABLED-}" ] ||
	exit 0

filename="$1" && shift
filetype="$(file -bLz -- "$filename")"

cmd_unpack=
case "$filetype" in
	*bzip\ compressed*|*bzip2\ compressed*)
		cmd_unpack='/bin/bzcat -q --'
		;;
	*gzip\ compressed*)
		cmd_unpack='/bin/zcat -q --'
		;;
	*xz\ compressed*)
		cmd_unpack='/usr/bin/xzcat -q --'
		;;
	*compress\'d\ data*)
		cmd_unpack='/usr/bin/uncompress -c'
		;;
	*)
		[ -z "${FILENAME_IS_COMPRESSED_BY_LZMA-}" ] ||
			cmd_unpack='/usr/bin/lzcat -q --'
		;;
esac

cmd_f=
[ -z "$cmd_unpack" ] || cmd_f=/dev/stdin

cmd=
cmd_args=
cmd_need_filename=

case "$filetype" in
	directory)
		cmd='/usr/bin/stat'; cmd_args=''
		;;
	PNG\ image*|JPEG\ image*|GIF\ image*|TIFF\ image*|X\ pixmap\ image*|MS\ Windows\ icon*)
		cmd='/usr/bin/identify'; cmd_args=''
		;;
	*tar\ archive*)
		cmd='/bin/tar'; cmd_args='-tvf'
		cmd_unpack=
		;;
	*cpio\ archive*)
		cmd='/bin/cpio'; cmd_args='-tv --quiet -I'
		;;
	*Zip\ archive*)
		cmd='/usr/bin/unzip'; cmd_args='-l -qq --'
		;;
	*Zoo*)
		cmd='/usr/bin/zoo'; cmd_args='xqp'
		;;
	*ARC*)
		cmd='/usr/bin/arc'; cmd_args='pn'
		;;
	*LHa*)
		cmd='/usr/bin/lha'; cmd_args='p'
		;;
	*RAR*)
		cmd='/usr/bin/unrar'; cmd_args='l'
		;;
	RPM\ v*)
		cmd='/usr/bin/rpm'; cmd_args='-qilvp --lastchange --'
		;;
	current\ ar\ archive*)
		cmd='/usr/bin/ar'; cmd_args='tv'
		cmd_need_filename=1
		;;
	ELF\ *|data*)
		cmd='/usr/bin/hexdump'; cmd_args='-C --'
		cmd_f=
		;;
	Linux/i386*|MS-DOS\ executable*|MS-Windows*|Win95\ executable*)
		cmd='/usr/bin/strings'; cmd_args='--'
		;;
	*troff\ or\ preprocessor\ input\ text*)
		cmd='/usr/bin/nroff'; cmd_args='-t -mandoc --'
		;;
	*OpenDocument\ Text*|*OpenOffice.org*\ document*)
		cmd='/usr/bin/odt2txt'; cmd_args=
		cmd_need_filename=1
		;;
esac

for f in "${0%/*}"/lesspipe-* "${HOME-}/.less"/lesspipe-*; do
	[ ! -s "$f" ] || . "$f"
done

if [ -n "$cmd" ]; then
	[ -x "$cmd" ] ||
		exit 0

	if [ -n "$cmd_unpack" ]; then
		[ -n "$cmd_need_filename" ] ||
			exec $cmd_unpack "$filename" |$cmd $cmd_args $cmd_f 2>&1
	else
		exec $cmd $cmd_args "$filename" 2>&1
	fi
else
	[ -z "$cmd_unpack" ] ||
		exec $cmd_unpack "$filename"
fi
