#!/bin/bash
#
# List, add, update or delete files in a gzipped, bzipped or compressed
# tar file.  Used by emacs archive-mode to update compressed archives.
#
# Copyright (c) 1998, Massimo Dal Zotto <dz@cs.unitn.it>
#
# This file is distributed under the GNU General Public License
# either version 2, or (at your option) any later version.

verbose=""
switches=""
function="--list"

function usage() {
    echo "Usage:  $0 [-v] [<function>] [-f] <archive> <files...>"
    echo ""
    echo "function: -l|--list       (default)"
    echo "          -r|--append"
    echo "          -u|--update"
    echo "          --delete"
    echo ""
}

while [ "$1" ]; do
	case "$1" in
	-h)
		usage
		shift
		exit
		;;
	-f)
		archive="$2"
		shift 2
		;;
	-v)
		verbose="-v"
		shift
		;;
	-t|--list)
		function="--list"
		shift
		;;
	-r|--append)
		function="--append"
		shift
		;;
	-u|--update)
		function="--update"
		shift
		;;
	--delete)
		function="--delete"
		shift
		;;
	-*)
		switches="$switches $1"
		shift
		;;
	*)
		if [ ! "$archive" ]; then	# may have been set with -f
		    archive="$1"
		    shift
		fi
		break
		;;
	esac
done
test ! "$archive" && { usage; exit 1 }
test ! "$*" && test "$function" != "--list" && { usage; exit 1 }

# Find archive extension
ext=${archive##*.}
if [ "$ext" = "gz" -o "$ext" = "bz2" -o "$ext" = "z" -o "$ext" = "Z" ]; then
	x=${archive%.*.$ext}
	ext=${archive#$x.}
fi

case "$archive" in
    *.tar.gz|.tar.z|*.tgz|*.taz)
	compress=gzip
	uncompress=gunzip
	;;
    *tar.bz2|*.tbz)
	compress=bzip2
	uncompress=bunzip2
	;;
    *.tar.Z)
	compress=compress
	uncompress=uncompress
	;;
    *)	echo "Invalid archive extension: $archive"
	exit 1
	;;
esac

tmpfile=$archive.tmp.$$
newfile=$archive.new.$$
trap "rm -f $tmpfile $newfile" 0 1 2 3 5 10 13 15

# Special case for --list to avoid writing a temporary file
if [ "$function" = "--list" ]; then
    $uncompress < $archive | tar --list $verbose $switches -f - "$@"; rc=$?
    exit $rc
fi

# Uncompress the archive
if ! $uncompress < $archive > $tmpfile; then
    exit 1
fi

# Update the temporary file
case $function in
    --delete)
	tar --delete $verbose $switches -f $tmpfile "$@"; rc=$?
	if [ $rc != 2 ]; then
	    exit $rc
	fi
	;;
    --append)
	tar --delete $switches -f $tmpfile "$@" 2>/dev/null
	tar --append $verbose $switches -f $tmpfile "$@"; rc=$?
	if [ $rc != 0 ]; then
	    exit $rc
	fi
	;;
    --update)
	# don't delete files from archive
	tar --update $verbose $switches-f $tmpfile "$@"; rc=$?
	if [ $rc != 0 ]; then
	    exit $rc
	fi
	;;
esac

# Compress the temporary file
if ! $compress < $tmpfile > $newfile; then
    exit 1
fi

# Rename the temporary file
if ! mv -f $newfile $archive; then
    exit 1
fi

# end of file
