#!/bin/dash
# (C) James Budiono 2014, 2015
# compatible replacement of the original pupzip
#
# Note: internally uses xarchiver
# one argument: open archive, more than one argument: add create new archive 
#

### configuration
ARCHIVER=${DEFAULTARCHIVER:-xarchiver}
ARCHIVER_ADD="$ARCHIVER -d" # add/create new files
TMP=/tmp/pupzip.$$

### helpers ###

# $1-path output $TMPTAR
convert_rpm() {
	file=${1##*/}; filename=${file%.*}; TMPTAR="/tmp/${filename}.tar"
	mkdir -p "$TMP/$filename" &&
	rpm2cpio "$1" | ( cd "$TMP/$filename"; cpio -d -i -m 2>/dev/null) &&
	tar -C "$TMP" -cf $TMPTAR "$filename" &&
	rm -rf "$TMP"
}

# $1-path output $TMPTAR
convert_deb() {
	file=${1##*/}; filename=${file%.*}; TMPTAR="/tmp/${filename}.tar"
	mkdir -p "$TMP/$filename" &&
	undeb -x "$1" "$TMP/$filename" &&
	tar -C "$TMP" -cf $TMPTAR "$filename" &&
	rm -rf "$TMP"
}

# $1-method $2-file
convert_to_tarball() {
	file=${2##*/}
	Xdialog --no-buttons --infobox "Converting ${file} to tarball, please wait ..." 0 0 1000000 &
	XPID=$!
	
	case $1 in
		rpm) convert_rpm "$2" ;;
		deb) convert_deb "$2" ;;
	esac
	retval=$?

	kill $XPID
	[ $retval -ne 0 ] && Xdialog --infobox "${file} cannot be opened." 0 0 10000
	return $retval
}


### main ###
[ -z $DISPLAY ] && echo "You need desktop to run this." && exit 1
case $# in
	0) exec $ARCHIVER ;; # no param, launch archiver directly
	1) case "$1" in 
		--help) echo "Pupzip-compatible universal archiver." ;;
		*) file=${1##*/}; fileext=${file#*.}
		   case "$fileext" in
		    *zip|*tar|*tgz|*tbz|*tbz2|*txz|*tar.gz|*tar.bz2|*tar.xz|*rar|*7z) exec $ARCHIVER "$1" ;;
			*gz|*bz2|*xz|*lzma) 
				if Xdialog --yesno "Do you want to decompress ${file}?
									Original file will be deleted." 0 0; 
				then
					Xdialog --no-buttons --infobox "Decompressing ${file}, please wait ..." 0 0 1000000 &
					XPID=$!
					case "$fileext" in
						*gz)   gunzip  "$1" ;;
						*bz2)  bunzip2 "$1" ;;
						*xz)   unxz "$1" ;;
						*lzma) unlzma "$1" ;;
					esac
					kill $XPID
				fi ;;
			*rpm)   convert_to_tarball rpm "$1" && $ARCHIVER $TMPTAR; rm -f $TMPTAR ;;
			*deb)   convert_to_tarball deb "$1" && $ARCHIVER $TMPTAR; rm -f $TMPTAR ;;
			*delta) exec xdelta_gui "$1" ;;
			*bfe)   exec bcrypt_gui "$1" ;;
			*)      exec $ARCHIVER_ADD "$1" ;;
		   esac ;;
	   esac ;;
	*) exec $ARCHIVER_ADD "$@" ;;
esac

