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

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

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

### 2. Contains encrypted files?
if zipinfo -v "$1" | grep -q -m1 -E 'status:[[:space:]]+encrypted'; then
	PASSWORD="$(Xdialog --stdout \
						--title "$TITLE" \
						--backtitle "Archive contains encrypted file(s)." \
						--password \
						--inputbox "Enter password:" 0 0)"
	[ $? -ne 0 ] && { rmdir "$TARGETDIR"; exit; }
	PASSCMD="-P $PASSWORD"
else
	PASSCMD=""
fi

### 3. extract
printf "Extracting ${1} in ${TARGETDIR}\n===\n"
#if unzip $PASSCMD -o "$1" -d "$TARGETDIR" 2> /dev/null | sed 's/[^:]*://' ; then
if unzip $PASSCMD -o "$1" -d "$TARGETDIR"; then
	printf "===\nExtraction successful."
else
	printf "===\nExtraction failed!"
fi
) > $out &

Xdialog --title "$TITLE" --no-cancel --tailbox $out 25 80
rm $out
