#!/bin/sh

# ipkg-extract -- extract a ipk-package to a directory
# bz Junya Keller <zaurus@h2o.ch> 2003-01-04
# tested on zaurus with sharp rom 2.38G / oz3.0
# - extracts packages to vfat-drives (uses control instead of CONTROL)
# - supports ar-compressed packages, if ar installed on system
# - extracts non-standard files in archive

# show (optional msg &) usage
ipkg-extract-usage() {
	[ $# -gt 0 ] && echo "$*"
	echo "
Usage: ipkg-extract <package.ipk> [<destination_directory>]" >&2
	exit 1
}

# get parameters pkg and dest_dir
case $# in
1)
	dest_dir=.
	;;
2)
	dest_dir=$2
	;;
*)
	ipkg-extract-usage
	;;
esac
pkg=$1

# check if pkg and dest_dir are available
if [ ! -f "$pkg" ]; then
	ipkg-extract-usage "Error: File \"$1\" does not exist or not readable"
fi
if [ ! -d "$dest_dir" ]; then
	ipkg-extract-usage "Error: Destination directory \"$dest_dir\" does not exist"
fi

# get full path to pkg
owd=`pwd`
pkg_dir=`echo "$pkg"|sed "s/[^/]*$//"`
# cd must be quoted here!
cd "$pkg_dir"
pkg_dir=`pwd`
pkg=`echo "$pkg"|sed "s/^.*\///"`
pkg="$pkg_dir/$pkg"

# get full path to dest_dir
cd $owd
cd $dest_dir
dest_dir=`pwd`

# create tmp_dir
tmp_dir=/tmp/IPKG_EXTRACT.$$
mkdir $tmp_dir

# check if the compression of pkg is tgz or ar
compr=
[ -n "`tar -tzf $pkg 2>/dev/null`" ] && compr=tgz
[ -n "`ar -t $pkg 2>/dev/null`" ] && compr=ar
if [ -z "$compr" ]; then
	echo "Error: Package corrupt or no suitable extractor found. The commands tar, gzip (and ar to extract newer ipk's) must be available on your system." >&2
	exit 1
fi

# extract pkg to tmp_dir
cd $tmp_dir
[ "$compr" = "tgz" ] && tar -xzf $pkg
[ "$compr" = "ar" ] && ar -x $pkg

# create directories in dest_dir
cd $dest_dir
pkg_name=`basename $pkg .ipk`
mkdir ./$pkg_name 2>/dev/null
cd ./$pkg_name
mkdir CONTROL 2>/dev/null
ctrl_name=
[ -d ./CONTROL ] && ctrl_name=CONTROL
# vfat on linux: CONTROL --> control
[ -d ./control ] && ctrl_name=control

# extract files to dest_dir
cd $dest_dir/$pkg_name
mv $tmp_dir/debian-binary $dest_dir/$pkg_name 2>/dev/null || echo "Warning: Couldn't extract debian-binary" >&2
tar -xzf $tmp_dir/data.tar.gz 2>/dev/null || echo "Warning: Couldn't extract data.tar.gz" >&2
rm $tmp_dir/data.tar.gz 2>/dev/null
cd $dest_dir/$pkg_name/$ctrl_name
tar -xzf $tmp_dir/control.tar.gz 2>/dev/null || echo "Warning: Couldn't extract control.tar.gz" >&2
rm $tmp_dir/control.tar.gz 2>/dev/null

# extract non-standard files
nstd_files=`ls -A $tmp_dir`
if [ -n "$nstd_files" ]; then
	cd $tmp_dir
	mv $nstd_files $dest_dir/$pkg_name
	echo "Warning: Extracted non standard files" >&2
fi

# delete tmp_dir & success msg
rmdir $tmp_dir
echo "Contents of $pkg extracted to $dest_dir/$pkg_name"
