#!/bin/sh
#	Thierry Vignaud <tvignaud@mandrakesoft.com>
#		v1.1: fix space usage
#		v1.2: keep source file, not bz2 one if eof while decompressing
#		v1.3: reduce used cpu time

compress ()
{	echo -n "Compressing $1 ... "
	SIZE=$(du $1|cut -f 1 -d "	")
	SIZE_o=$(du -b $1|cut -f 1 -d "	")
	if [ -f $TARGET ]
	then
		echo "$TARGET already exists !!"
		return
	fi
	zcat $1 | bzip2 -9 > $TARGET
	MY_STATUS=( ${PIPESTATUS[*]}  ) 
	if [ "${MY_STATUS[0]}" != 0 ]; then
		echo "Corrupted source file ($1) !"
		rm -f $TARGET
		return
	fi
	if [  "${MY_STATUS[1]}" != "0" ]; then
		echo "error while bziping !"
		rm -f $TARGET
		return
	fi
	SIZE2=$(du $TARGET|cut -f 1 -d "	")
	SIZE2_o=$(du -b $TARGET|cut -f 1 -d "	")
	if [ $SIZE_o -lt $SIZE2_o ]
	then
		echo "=> $TARGET is bigger than $1 ($SIZE"kb" => $SIZE2"kb") !!!"
		rm -f $TARGET
	else
		echo "=> $TARGET ($SIZE"kb" => $SIZE2"kb")"
		rm -f $1
	fi
	
}

while [ "$1" != "" ]
do
	case $1 in
		*.tgz)
			TARGET=$(echo $1|sed 's/\.tgz$/\.tar\.bz2/')
			compress $1
		;;
		*.Z)
			TARGET=$(echo $1|sed 's/\.Z$/\.bz2/')
			compress $1
		;;
		*.gz)
			TARGET=$(echo $1|sed 's/\.gz$/\.bz2/')
			compress $1
		;;
		*.bz2)	echo "$1: already compressed!";;
		*)	echo "$1: unknown file extension => ignored"
	esac
	shift
done
