#!/bin/sh
#==============================================================================
# Copyright (C) 1999-2002 MandrakeSoft (tvignaud@mandrakesoft.com)
# By Thierry Vignaud <tvignaud@mandrakesoft.com>
#
# 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, 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.
#
# The GNU General Public License can be read at
# http://www.fsf.org/copyleft/gpl.html
#==============================================================================
#
#  Changelog:
#  ----------
#  v1.0: original release
#  v1.1: fix space usage (use pipe rather than temp file)
#  v1.2: keep source file, not bz2 one if eof while decompressing
#  v1.3: reduce used cpu time (decompressing only one time;
#        source crc error 're detected through PIPESTATUS)
#  v1.4: add zip support on popular^h^h^h^h^hGwenole request
#  v1.5: - make zip method acting as z one (remove orginal file,
#          keeping only smalest file, displaying size gain, ...)
#          thus giving occasion to factorize some common code
#        - check that the source file
#        - handle corrupted zip file
#        - comment the script and verbos-ize() some old changes
#        - use cheaper shell tests
#        - add GPL reference
#        - update online help to reflect optional options and newer
#          supported formats
#        - remove dependancy on sed by using ${1%old}new_extension

force=


src_err_msg ()
{
	if [ "$2" != 0 ]; then
		echo "Corrupted source file ($1) !"
		rm -f $TARGET
		STATUS=1
	fi
}

gz_compr ()
{	zcat $1 | bzip2 -9 > $TARGET
	MY_STATUS=( ${PIPESTATUS[*]} ) 
	src_err_msg $1 ${MY_STATUS[0]}
	if [[ "${MY_STATUS[1]}" != "0" ]]; then
		echo "error while bziping !"
		STATUS=1
	fi
}

zip_compr ()
{
	[[ -z "$TMPDIR" ]] && TMPDIR=$TMP
	MY_TMP=$(mktemp -d $TMPDIR/bzme.XXXXXX)
	unzip -qd $MY_TMP $1
	src_err_msg $1 $?
	(cd $MY_TMP; tar cf - .)|bzip2 > $TARGET
	MY_STATUS=( ${PIPESTATUS[*]} ) 
	if [[ "${MY_STATUS[1]}" != "0" ]]; then
		echo "error while bziping !"
		STATUS=1
		# We return since bzip2 error will propagate to tar via
		# read erro (prevent double error message)
		return
	fi
	if [[ "${MY_STATUS[0]}" != "0" ]]; then
		echo "error while taring !"
		STATUS=1
	fi
	# Removing temporary files
	rm -fr $MY_TMP
}

compress ()
{	echo -n "Compressing $1 ... "
	if [[ ! -f $1 ]]; then
		echo "Source file doesn't exist"
		return
	fi
	STATUS=0
	SIZE=$(du $1|cut -f 1 -d "	")
	SIZE_o=$(du -b $1|cut -f 1 -d "	")
	if [[ -f $TARGET ]];	then
		if [[ -n $force ]];then
			rm -f $TARGET
		else
			echo "$TARGET already exists !!"
			echo "Use -f to force it"
			return
		fi
	fi
	# Do the real compression job
	$METHOD $1
	# if there was an error
	if [[ $STATUS = 1 ]]; then
		rm -f $TARGET
		return
	fi
	# Compare size in order to only keep the smallest file
	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 getopts f opt
  do
  case "$opt" in
      f) force="yes";;
      *)
	  echo "Usage: bzme [-f] file.*.({,t}gz|Z|zip)"
	  exit 1
	  ;;
  esac
done
shift $((OPTIND - 1))

while [[ "$1" != "" ]]
do
	#default method is gz,.Z,.z,..
	METHOD=gz_compr
	case $1 in
		*.tgz)
			TARGET=${1%.tgz}.tar.bz2
			compress $1
		;;
		*.Z)
			TARGET=${1%.Z}.bz2
			compress $1
		;;
		*.gz)
			TARGET=${1%.gz}.bz2
			compress $1
		;;
		*.bz2)	echo "$1: already compressed!";;
		*.zip)
			METHOD=zip_compr
			TARGET=${1%.zip}.tar.bz2
			compress $1
			;;
		*)	echo "$1: unknown file extension => ignored"
	esac
	shift
done
