#! /bin/sh
# repackage upstream source to exclude unreleased embedded library boost/process
# should be called "repack.sh <original_sources> [<output_directory>]

## usage message
usage() {
    echo "Usage: $1 <original_sources> [<ouput_directory>]"
    echo "  repack upstream sources into debian compliant tarball"
}

## check that we are in working directory 
check_path() {
    if [ -d debian ]; then
        return
    else
        echo "please move to working directory (uncompressed sources)"
        echo "current path: $(pwd)"
        exit 1
    fi
}

main() {        
    check_path
    NAME=$(dpkg-parsechangelog | awk '/Source:/ { print $2 }')
    ORIG=$1
    if [ $2 ]; then
        OUTPUT=$(readlink -f $2) # canonicalize output path
    fi
    # extract version from upstream tarball
    VERSION=$(echo $ORIG | sed 's/.*diet-\([0-9.]\+\).tgz/\1/')

    # .0 upstream release sometimes don't get patch version in tarball name
    if [ ${#VERSION} -le 3 ]; then
        VERSION="$VERSION.0"
    fi

    # make sure that unpacked file will be cleansed
    DIR=$(mktemp -d tmpRepackXXXXXX)
    trap "rm -rf $DIR" QUIT INT EXIT
    DIR_DEL="$DIR/diet-$VERSION/src/Testing/third-party"
    
    # unpack upstream tarball
    tar xzf $ORIG -C $DIR

    CURRENT_DIR=$(pwd)
    TARGET="$CURRENT_DIR/diet_$VERSION.orig.tar.gz"
    
    cd $DIR
    # files to remove
    rm -rf $DIR_DEL
    # recompress tarball
    tar czvf $TARGET "diet-$VERSION"
    if [ -e $OUTPUT ]; then
        mv $TARGET $OUTPUT
    fi
    cd $CURRENT_DIR
}

# we should have at least one argument (upstream tarball)
if [ $# -ge 1 ]; then
    main $@
else
    usage $0
fi;

