#!/bin/sh
#
# zme
# Copyright (C) 2000  Dmitry V. Levin <ldv@fandra.org>
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

Usage_human()
{
	local h=`/usr/bin/du -h -- "$1"`
	echo "${h%	$1}"
}

Usage_bytes()
{
	/bin/ls -lL -- "$1" |/bin/awk '{print $5}'
}

Compress()
{
	if [ -f "$NAME" -o -L "$NAME" ]; then
		echo -E "${0##*/}: $NAME already exists, aborting"
		exit 2
	fi

	NAME2="$NAME$SUFFIX"
	if [ -f "$NAME2" -o -L "$NAME2" ]; then
		echo -E "${0##*/}: $NAME2 already exists, aborting"
		exit 2
	fi

	echo -nE "Compressing $FILE => $NAME2 "

	SIZE_h="$(Usage_human "$FILE")"
	SIZE_b="$(Usage_bytes "$FILE")"
	if [ -z "$SIZE_h" -o -z "$SIZE_b" ]; then
		echo -E "${0##*/}: failed to determine file size, aborting"
		exit 3
	fi
	if ! $UNARCHIVE -- "$FILE" >"$NAME"; then
		rm -f -- "$NAME"
		exit 1
	fi
	if ! $ARCHIVE -- "$NAME"; then
		rm -f -- "$NAME"
		exit 1
	fi
	touch -r "$FILE" -- "$NAME2"
	SIZE2_h="$(Usage_human "$NAME2")"
	SIZE2_b="$(Usage_bytes "$NAME2")"
	if [ "$SIZE_b" -le "$SIZE2_b" ]; then
		if [ "$SIZE_h" = "$SIZE2_h" ]; then
			if [ "$SIZE_b" = "$SIZE2_b" ]; then
				echo -nE "has same size as original ($SIZE_b)"
			else
				echo -nE "is bigger than original ($SIZE_b => $SIZE2_b)"
			fi
		else
			echo -nE "is bigger than original ($SIZE_h => $SIZE2_h)"
		fi
		echo " SKIP"
		rm -f -- "$NAME2"
	else
		if [ "$SIZE_h" = "$SIZE2_h" ]; then
			echo -nE "($SIZE_b => $SIZE2_b)"
		else
			echo -nE "($SIZE_h => $SIZE2_h)"
		fi
		echo " OK"
		rm -f -- "$FILE"
	fi
	
}

Compress_gzip()
{
	UNARCHIVE=bzcat
	ARCHIVE="gzip -9nf"
	SUFFIX=".gz"
	FILE="$1"
	Compress
}

Compress_bzip2()
{
	UNARCHIVE=zcat
	ARCHIVE="bzip2 -9f"
	SUFFIX=".bz2"
	FILE="$1"
	Compress
}

while [ -n "$1" ]; do
	case "$1" in
		*.tgz)
			NAME="${1%.tgz}.tar"
			Compress_bzip2 "$1"
			;;
		*.tbz2)
			NAME="${1%.tbz2}.tar"
			Compress_gzip "$1"
			;;
		*.gz)
			NAME="${1%.gz}"
			Compress_bzip2 "$1"
			;;
		*.Z)
			NAME="${1%.Z}"
			Compress_bzip2 "$1"
			;;
		*.bz2)
			NAME="${1%.bz2}"
			Compress_gzip "$1"
			;;
		*)	echo -E "${0##*/}: $1: unknown file suffix, ignored"
			;;
	esac
	shift
done
