#!/bin/sh

usage()
{
    echo "This script unpack ooo source tarballs generated by ooo-pack-sources and"
    echo "move all modules into a single dir"
    echo
    echo "Usage: ${0##*/} [--help] version"
    echo
    echo "Parameters:"
    echo
    echo "	version:     version of the source tarballs, e.g. 3.3.0.2"
}

version=
tarball_prefix="ooo-build"

while test -n "$1" ; do
    case "$1" in
	--help)
	    usage
	    exit 0;
	    ;;
	-*)
	    echo "Error: unknown option: $1"
	    exit 1;
	    ;;
	*)
	    if test -z "$version" ; then
		version="$1"
	    else
		echo "Error: unknown parameter: $1"
	    fi
	    ;;
    esac
    shift
done

if test -z "$version" ; then
    echo "Error: Please, define the version. Try --help"
    exit 1;
fi

outdir="$tarball_prefix-$version"

if test -d "$outdir" ; then
    echo "Warning: output directory already exists: $outdir"
	printf "Could I replace it? (y/n)"
    read answer
    if test $answer != "y" ; then
        echo "	Exiting. You must answer \"y\" to continue"
	exit 1;
    fi
    rm -rf "$outdir"
fi

mkdir -p "$outdir"

for tarball in $tarball_prefix-$version-*.tar.bz2 ; do
    echo -n "Unpacking $tarball"
    tempdir=`mktemp -d "$outdir/$tarball_prefix-$version-XXXXXX"`
    checkpoint=`du $tarball | cut -f 1`
    checkpoint=$(($checkpoint / 15 + 1))
    tar -xf $tarball -C $tempdir --checkpoint=$checkpoint 2>&1 | awk '{ ORS="" ; printf "." ; fflush() }'
    echo
    mv $tempdir/*/* $outdir
    rm -rf $tempdir
done
