#!/bin/bash
#
# Unpack compressed examples from the packaged documentation
# into a directory where the user can compile and/or run them.

WX_EXAMPLES_DIR="/usr/share/doc/wx=V-examples/examples"

usage() {
    echo "$0 [subdir [subdir] ...] dest_dir"
    echo "    subdir   - a subdir of $WX_EXAMPLES_DIR to unpack."
    echo "    dest_dir - location for the unpacked examples."
    echo
    echo "If no subdirs are supplied explicitly, all examples will be unpacked."
    exit 1
}

if [ $# -lt 1 ]; then
    usage
fi 

while [ $# -gt 1 ]; do
    SUBDIRS="$SUBDIRS $1"
    shift
done

DESTDIR="$1"

if [ -e $DESTDIR ]; then
    echo "Destination $DESTDIR already exists. Cowardly exiting."
    exit 2
fi

if [ -z "$SUBDIRS" ]; then
    for d in $(cd $WX_EXAMPLES_DIR 2> /dev/null && ls -d * 2> /dev/null); do
        [ -d "$WX_EXAMPLES_DIR/$d" ] && SUBDIRS="$SUBDIRS $d"
    done
else
    for d in $SUBDIRS; do
    	if [ -d "$WX_EXAMPLES_DIR/$d" ]; then
	    _SUBDIRS="$d"
	else
	    echo "Subdir $WX_EXAMPLES_DIR/$d does not exist.  Skipping."
	fi
    done
    SUBDIRS="$_SUBDIRS"
fi

if [ -z "$SUBDIRS" ]; then
    echo "Nothing to copy from $WX_EXAMPLES_DIR.  Aborting."
    exit 1
fi

mkdir -p $DESTDIR
for d in $SUBDIRS; do
    echo "Copying $WX_EXAMPLES_DIR/$d to $DESTDIR"
    cp -pr "$WX_EXAMPLES_DIR/$d" "$DESTDIR"
done

echo -n "Unpacking... "
find $DESTDIR -name "*.gz" -exec gunzip {} \;
echo "done."