#!/bin/dash

### config
APPTITLE=Compress
COMPRESSOR=xz # or bzip2 or gzip
COMP_EXT=xz   # or bz2 or gz
USE_TAR=      # by default don't use tar
OUTPUT="$1"   # default output name is the first source

### helper
dlg() {
	Xdialog --stdout --title "$APPTITLE" "$@"
}

### main
# if multiple arguments, use tar and ask the output filename
if [ $# -gt 1 ]; then
	if ! OUTPUT=$(dlg --back-title "Choose the output filename" --fselect "" 0 0); then 
		dlg --infobox "Cancelled." 0 0 10000
		exit
	fi
	USE_TAR=1
fi

# if any of sources are already compressed, use tar
# if any of the sources are directory, use tar
for p; do
	case "$1" in
		*.gz|*.bz2|*.xz|*.lzma|*.lzo)
			USE_TAR=1 ;;
	esac
	[ -d $p ] && USE_TAR=1
done

# sanity check
[ $USE_TAR ] && OUTPUT=${OUTPUT}.tar
if [ -f $OUTPUT.$COMP_EXT ]; then
	if dlg --yesno "$OUTPUT already exist, do you want to continue?" 0 0; then
		rm $OUTPUT.$COMP_EXT
	else
		exit
	fi
fi

Xdialog --title-no-buttons --infobox "Compressing, please wait ..." 0 0 1000000 &
XPID=$!
if [ $USE_TAR ]; then
	> ${OUTPUT}
	for p; do
		p=${p#$PWD/}
		tar -rf ${OUTPUT} "$p"	
	done
fi

$COMPRESSOR $OUTPUT
kill $XPID
Xdialog --title "$APPTITLE" --infobox "Done. Output is $OUTPUT.$COMP_EXT." 0 0 10000
