#!/bin/dash

### config
APPTITLE=Compress
COMPRESSOR=zip # or bzip2 or gzip
COMP_EXT=zip   # 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, 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
fi

# sanity check
if [ -f "$OUTPUT.$COMP_EXT" ]; then
	if dlg --yesno "$OUTPUT.$COMP_EXT 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=$!
# create and empty zip file
printf "PK\005\006\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" > "${OUTPUT}.$COMP_EXT"
for p; do
	[ "${p%/*}" ] && cd "${p%/*}" || cd /
	zip -y -r "$OUTPUT.$COMP_EXT" "${p##*/}"
done

kill -0 $XPID 2>/dev/null && kill $XPID
Xdialog --title "$APPTITLE" --infobox "Done. Output is $OUTPUT.$COMP_EXT." 0 0 10000
