#!/bin/dash
# (C) James Budiono 2014
# License: GPL Version 3 or later.
#
### extract contents of a tarball to current directory
# $1 - tarball
# $2 - optional target directory

[ -z "$1" ] && echo "Usage: ${0##*/} package [targetdir]" && exit
out=$(mktemp -p /tmp extracttarball.XXXXXXXX)

(
### 1. prepare
TARGETDIR=$(readlink -f "$1")
case "$TARGETDIR" in
	*.t?z)     TARGETDIR="${TARGETDIR%.t?z}"     ;;
	*.tar.?z)  TARGETDIR="${TARGETDIR%.tar.?z}"  ;;
	*.tar.bz2) TARGETDIR="${TARGETDIR%.tar.bz2}" ;;
	*) TARGETDIR="${TARGETDIR}.extracted"        ;;
esac
[ "$2" ] && TARGETDIR="$2"
mkdir -p "$TARGETDIR"

### 2. extract
printf "Extracting ${1} in ${TARGETDIR}\n===\n"
if tar -xvf "$1" -C "$TARGETDIR" 2>/dev/null; then
	printf "===\nExtraction successful.\n"
else
	printf "===\nExtraction failed!\n"
fi 
) > $out & 

Xdialog --title "Extract Tarball $1" --no-cancel --tailbox $out 25 80
rm $out
