#!/bin/bash
#
# Release packing script for OpenPTC development kits
#
# usage: "release [destination]"
#
# defaults:
# 
# destination = "release"
#


# current version
VERSION="1.0.0"

# get kit version: "get_kit_version"
function get_kit_version
{
    # look for "changes.txt"
    CHANGES="changes.txt"
    if [ ! -e "$CHANGES" ]; then
        
        # look for "CHANGES"
        CHANGES="CHANGES"
        if [ ! -e "$CHANGES" ]; then
        
            # error message
            echo "could not find changes file"
            exit
            
        fi
        
    fi

    # grep for lines starting with "Version" keep the first match and cut the version number
    VERSION=$(grep -h '^Version' $CHANGES | sed -n 1p | cut -d' ' -f2)
}

# package kit: "package_kit name [depth]"
function package_kit
{
    # input variables
    name=$1
    depth=${2:-1}

    # check that the kit directory exists
    if [ -d "$name" ]; then

        # enter directory    
        cd $name
        
        # get kit version
        get_kit_version
    
        # package the kit
        "$script_directory"package ptc-$name $VERSION $depth
        
        # setup package name    
        package=ptc-$name-$VERSION
        
        # copy the package files
        cp $package/* ../release
        
        # remove the temporary directory
        rm -rf $package
        
        # leave directory
        cd ..
    
    else
    
        # error message
        echo "kit directory does not exist"
        exit        
    
    fi
}


# get release directory
RELEASE=${1:-release}

# make the release directory
rm -rf release
mkdir release

# get script directory
script_directory=${0%/*}
if [ -n "$script_directory" ]; then
    script_directory="$script_directory/"
fi

# package the kits
package_kit "c" 1
package_kit "demos" 2
package_kit "documentation" 1
package_kit "examples" 2
package_kit "hermes" 1
package_kit "java" 1
package_kit "merger" 1
package_kit "porting" 1
package_kit "testing" 1

# package the scripts kit
if [ -d 'scripts' ]; then
    
    # enter directory
    cd scripts
    
    # get kit version
    get_kit_version

    # create temporary directory
    rm -rf ptc-scripts-$VERSION
    mkdir ptc-scripts-$VERSION

    # copy all files to the new directory
    cp * ptc-scripts-$VERSION

    # tar the scripts
    tar -vcf ptc-scripts-$VERSION.tar ptc-scripts-$VERSION
    
    # compress the tarfile
    gzip -9 ptc-scripts-$VERSION.tar
    
    # move to release directory
    mv ptc-scripts-$VERSION.tar.gz ../$RELEASE
    
    # remove temporary directory
    rm -rf ptc-scripts-$VERSION
    
    # leave directory
    cd ..
    
fi
