#!/bin/dash
# jamesbond 2015
# MIT license
#
# Usage $1-deb $2-path to decompress
#

usage() {
	cat << EOF
Usage: undeb [options] /path/to/deb.deb dir-to-decompress
Options are:
    -x extract package contents (default)
    -X extract package contents, verbose
    -c list package contents
    -e extract package control files
EOF
	exit 1;
}

### args processing
DEB= TGT= CMD= VERBOSE=
for p; do 
	# process the same option as busybox dpkg-deb
	case "$p" in
		-c) CMD=list ;;
		-e) CMD=extract-control ;;
		-x) CMD=extract ;;
		-X) CMD=extract VERBOSE=v ;;
		-h) usage ;;
		*) [ -z "$DEB" ] && DEB="$p" && continue ||
		   [ -z "$TGT" ] && TGT="$p" ;;
	esac
done
#echo $CMD-$VERBOSE-$DEB-$TGT
[ -z "$CMD" ] && CMD=extract
if ! [ "$DEB" ] || ! [ "$TGT" ]; then usage; fi
! [ -d "$TGT" ] && echo "$TGT does not exist." && exit 2

### which AR to use
[ -z $AR ] && type ar > /dev/null && AR="ar"
[ -z $AR ] && type busybox > /dev/null && AR="busybox ar"
[ -z $AR ] && echo "Cannot find 'ar', needed to work." && exit 3

### do work
DEB="$(readlink -f "$DEB")"
cd "$TGT"
$AR -x "$DEB"
case $CMD in
	extract) tar -${VERBOSE}xf data.tar* ;;
	extract-control) tar -xf control.tar* ;;
	list) tar -tf data.tar* ;;
esac
rm debian-binary control.tar* data.tar*
