#!/bin/dash

### config
APPTITLE=Compress
COMPRESSOR=${COMPRESSOR:-xz} # or bzip2 or gzip
COMP_EXT=${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" "$@"
}
die() {
	dlg --infobox "$1" 0 0 10000
	exit 1
}

### main
[ $# -eq 0 ] && die "Usage: ${0##*/} file [file ...]"

# if multiple arguments, use tar and ask the output filename
if [ $# -gt 1 ]; then
	if ! OUTPUT=$(dlg --backtitle "Choose the output filename (don't provide extension)" --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 -k "$OUTPUT"
[ $USE_TAR ] && rm -f "$OUTPUT"
kill -0 $XPID 2>/dev/null && kill $XPID
Xdialog --title "$APPTITLE" --infobox "Done. Output is $OUTPUT.$COMP_EXT." 0 0 10000
