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

### configuration
APPTITLE="Pupzip"
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 --title="$APPTITLE" --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 --title="$APPTITLE" --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##*/}
		   case "$(echo "$file" | tr '[:upper:]' '[:lower:]')" in
		    *.zip|*.tar|*.tgz|*.tbz|*.tbz2|*.txz|*.tar.gz|*.tar.bz2|*.tar.lzma|*.tar.xz|*.tar.z|*.rar|*.7z|*.cpio) exec $ARCHIVER "$1" ;;
			*.gz|*.bz2|*.xz|*.lzma) 
				if result="$(Xdialog --title="$APPTITLE" --stdout --check "Delete original file after successful decompression" on \
							--yesno "Do you want to decompress ${file}?" 0 0)"; 
				then
					[ "$result" = "checked" ] && opt='' || opt='-k'
					Xdialog --title="$APPTITLE" --no-buttons --infobox "Decompressing ${file}, please wait ..." 0 0 1000000 &
					XPID=$!
					case "$(echo "$file" | tr '[:upper:]' '[:lower:]')" in
						*.gz)   cmnd='gunzip' ;;
						*.bz2)  cmnd='bunzip2' ;;
						*.xz)   cmnd='unxz' ;;
						*.lzma) cmnd='unlzma' ;;
					esac
					result="$($cmnd $opt "$1" 2>&1)"
					retval=$?
					kill -0 $XPID 2>/dev/null && kill $XPID
					if [ $retval -ne 0 ]; then
						Xdialog --title="$APPTITLE" --backtitle "Error" --infobox "$result" 0 0 1000000
					fi
				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

