usage()
{
    echo "usage: xipk <ipkg-name> [<output-dir>]"
    echo ""
    echo "If <output-dir> is not specified then it will be"
    echo "derived from <ipkg-name> (i.e. .ipk stripped)"
    exit 1
}

IPKG=$1
DIR=$2
if [ -z "$IPKG" ]; then
    echo "xipk: error: you must specify an IPK"
    usage
fi
if [ "$IPKG" = "-h" ]; then
    usage
fi
if [ -z "$DIR" ]; then
    DIR=`basename "$IPKG" ".ipk"`
    if [ "$DIR" = "$IPKG" ]; then
        echo "xipk: error: $IPKG: invalid IPK name; cannot derive output dir name"
        exit 1
    fi
fi

if [ -d $DIR ]; then
    echo "xipk: error: $DIR: directory already exists; you must remove it first"
    exit 1
fi
if [ -e $DIR ]; then
    echo "xipk: error: $DIR: can't create output directory; file with the same name is present"
    exit 1
fi

CWD=`pwd`
mkdir $DIR
cd $DIR
tar zxf ../$IPKG

if [ -e ./debian-binary ]; then
    rm -f ./debian-binary
fi

if [ ! -e ./control.tar.gz ]; then
    echo "xipk: warning: 'control.tar.gz' file missing; this may not be a valid IPK"
else
    mkdir ./CONTROL
    cd ./CONTROL
    tar zxf ../control.tar.gz
    cd ..
    rm ./control.tar.gz
fi

if [ ! -e ./data.tar.gz ]; then
    echo "xipk: warning: 'data.tar.gz' file missing; this may not be a valid IPK"
else
    tar zxf ./data.tar.gz
    rm ./data.tar.gz
fi

cd $CWD
