#!/bin/sh -e

FILE="$1" && shift
CMD=
TYPE=`file -bL -- "$FILE"`

TMPFILE="$(mktemp -t "lessfile.XXXXXXXXXX")"
exit_handler()
{
	RETVAL=$?
	trap '' EXIT
	if [ -n "$TMPFILE" ]; then
		[ $RETVAL -eq 0 ] && echo "$TMPFILE" || rm -f -- "$TMPFILE"
	fi
	exit $RETVAL
}

trap exit_handler SIGHUP SIGINT SIGQUIT SIGTERM EXIT

cmd_unpack=
case "$TYPE" in
	*bzip\ compressed*|*bzip2\ compressed*)
		cmd_unpack='bzcat -q --'
		;;
	*gzip\ compressed*)
		cmd_unpack='zcat -q --'
		;;
	*[Xx][Zz]\ compressed*)
		cmd_unpack='xzcat -q --'
		;;
	*Zstandard\ compressed*)
		cmd_unpack='zstdcat -q --'
		;;
	*compress\'d\ data*)
		cmd_unpack='uncompress -c'
		;;
	*)
		[ -z "${FILENAME_IS_COMPRESSED_BY_LZMA-}" ] ||
			cmd_unpack='lzcat -q --'
		;;
esac

if [ -n "$CMD" ]; then
	CMD2=
	TYPE=`$CMD "$FILE" 2>/dev/null |file -b -`
	case $TYPE in
		*tar\ archive*)
			CMD2='tar -tvv'
			;;
		*cpio\ archive*)
			CMD2='cpio -tv'
			;;
		ELF\ *|*\ ELF\ *)
			CMD2='readelf'
			;;
		Linux/i386*|MS-DOS\ executable*|MS-Windows*|Win95\ executable*)
			CMD2='strings'
			;;
		*troff\ or\ preprocessor\ input\ text*)
			CMD2='nroff -t -mandoc'
			;;
	esac
	if [ -z "$CMD2" ]; then
		$CMD "$FILE" >"$TMPFILE" 2>&1
	else
		$CMD "$FILE" >"$TMPFILE" 2>&1 |$CMD2 2>&1
	fi
	exit
fi

case $TYPE in
	directory)
		CMD='stat'
		;;
	PNG\ image*|JPEG\ image*|GIF\ image*|TIFF\ image*|X\ pixmap\ image*|MS\ Windows\ icon*)
		CMD='identify'
		;;
	*tar\ archive*)
		CMD='tar -tvf'
		;;
	*cpio\ archive*)
		CMD='cpio -tv --quiet -I'
		;;
	Zip*)
		CMD='unzip -l -qq --'
		;;
	Zoo*)
		CMD='zoo xqp'
		;;
	ARC*)
		CMD='arc pn'
		;;
	LHa*)
		CMD='lha p'
		;;
	RAR*)
		CMD='unrar p'
		;;
	RPM\ v*)
		CMD='rpm -qilvp --lastchange --'
		;;
	current\ ar\ archive*)
		CMD='ar tv'
		;;
	ELF\ *|*\ ELF\ *)
		CMD='readelf -a --'
		;;
	Linux/i386*|MS-DOS\ executable*|MS-Windows*|Win95\ executable*)
		CMD='strings --'
		;;
	*troff\ or\ preprocessor\ input\ text*)
		CMD='nroff -t -mandoc --'
		;;
esac

if [ -n "$CMD" ]; then
	$CMD "$FILE" >"$TMPFILE" 2>&1
else
	exit 1
fi
