#!/bin/sh

pkg=$1
if [ "$pkg" = "" -o ! -e "$pkg" ]; then
    echo "no package supplied" 1>&2
   exit 1
fi

leadsize=96
o=`expr $leadsize + 8`
set `od -j $o -N 8 -t u1 $pkg`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`

sigsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $sigsize + \( 8 - \( $sigsize \% 8 \) \) \% 8 + 8`
set `od -j $o -N 8 -t u1 $pkg`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`

hdrsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $hdrsize`
set `od -j $o -N 8 -t u1 $pkg`
# --- gzip magic \037\213
if [ $2 -eq 31 -a $3 -eq 139 ]; then
	exec dd if=$pkg ibs=$o skip=1 | gunzip
# --- bzip2 magic BZh
elif [ $2 -eq 66 -a $3 -eq 90 -a $4 -eq 104 ]; then
	exec dd if=$pkg ibs=$o skip=1 | bunzip2
# --- XZ magic \xFD7zXZ\x00
elif [ $2 -eq 253 -a $3 -eq 55 -a $4 -eq 122 -a $5 -eq 88 -a $6 -eq 90 ]; then
	exec dd if=$pkg ibs=$o skip=1 | unxz
else
	# Most versions of file don't support LZMA, therefore we assume
	# anything not detected is LZMA
	DECOMPRESSOR=`which unlzma 2>/dev/null`
	case "$DECOMPRESSOR" in
	    /* ) ;;
	    *  ) DECOMPRESSOR=`which lzmash 2>/dev/null`
	         case "$DECOMPRESSOR" in
	             /* ) DECOMPRESSOR="lzmash -d -c" ;;
	             *  ) DECOMPRESSOR=cat ;;
	         esac
	         ;;
	esac
	exec dd if=$pkg ibs=$o skip=1 | $DECOMPRESSOR
fi
