#!/bin/dash
# (C) James Budiono 2013
# License: GPL Version 3 or later.
#
### extract content of pet package to current directory
# $1 - pet package
# $2 - optional target directory

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

(
### 1. check integrity (stolen from silent_petget)
fsize=$(( $(stat -c %s "$1") - 32 ))
cksum=$(dd if="$1" bs=$fsize skip=1 2> /dev/null)
echo -n Checking package integrity ...
if [ $(dd if="$1" bs=$fsize count=1 2> /dev/null | md5sum | awk '{print $1}') != $cksum ]; then
	echo " bad pet: checksum does not match."
	exit
fi
echo " good."

### 2. extract
TARGETDIR=$(readlink -f "$1")
TARGETDIR=${TARGETDIR%/*}
[ "$2" ] && mkdir -p "$2" && TARGETDIR="$2"
tar -xvf "$1" -C "$TARGETDIR" 2>/dev/null | awk -v fn="$1" -v dir="$TARGETDIR" '
BEGIN {
	print "Extracting " fn " in " dir "\n==="
}
{
	sub(/[^\/]*\/[^\/]*/,"",$1)
	for (i=1; i<=NF; i++) printf ("%s",$i)
	print ""
}
END {
	print "===\nExtraction completed."
}' 
) > $out &

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