#! /bin/sh

which orogen > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "'orogen' executable required, but not found, please check that you installed orogen"
    exit 1
fi

name=$1
if test -z "$name"; then
    if test -f manifest.xml; then
        # We assume that we are in an oroGen package already and should finalize
        # the creation
        orogen *.orogen
        orogen --clean
        git init
        git add .
        git commit -m 'initial commit by rock-create-orogen'
        exit 0
    else
        echo "usage: rock-create-orogen dirname"
        exit 1
    fi
fi
if test -e "$name"; then
    echo "$name already exists"
    exit 1
fi

# Test if name is a valid orogen component name
CMP_NAME_BASE=`echo "$name" | sed 's/.*\/\(.*\)/\1/g'`
CMP_NAME=`echo "$CMP_NAME_BASE" | grep -e '^[a-z0-9][a-z0-9_]*$'`

if test -z "$CMP_NAME"; then
    echo 
    echo "Invalid name ${CMP_NAME_BASE}: The component name must be all lowercase, can contain alphanumeric characters and underscores and start with a letter."
    echo 
    exit 1
fi

orogen create $name
cd $name
if test -z "$ROCK_TEMPLATE_PREFIX"; then
    ROCK_TEMPLATE_PREFIX=https://github.com/rock-core/base-templates-
    ROCK_TEMPLATE_SUFFIX=.git
    wget --timeout=5 https://raw.githubusercontent.com/rock-core/base-templates-cmake_lib/master/manifest.xml
    wget --timeout=5 https://raw.githubusercontent.com/rock-core/base-templates-cmake_lib/master/config_manifest.sh

    if [ $? != 0 ]; then
	echo
	echo "ROCK_TEMPLATE_PREFIX is not set and manifest can currently not be retrieved via github.org"
	echo "Verify your internet connnection or set ROCK_TEMPLATE_PREFIX to <your-rock-installation>/base/templates/"
	echo
	exit 2
    fi

    sh ./config_manifest.sh

else
    CMAKE_LIB_DIR=`echo "${ROCK_TEMPLATE_PREFIX}/cmake_lib" | sed 's/\/\//\//g'`
    if ! test -d "$CMAKE_LIB_DIR"; then
	echo
	echo "Package base/templates/cmake_lib is required, but could not be found at ${CMAKE_LIB_DIR}."
	echo "Please make sure you install package base/templates/cmake_lib."
	echo
	exit 3
    fi
	
    cp $CMAKE_LIB_DIR/manifest.xml .
    sh $CMAKE_LIB_DIR/config_manifest.sh
fi

echo
echo "oroGen package template successfully created. You should now cd in the"
echo "$name/ folder and edit the $name.orogen file to describe your types"
echo "and components."
echo "Then, re-run rock-create-orogen without arguments to finalize the package"
echo "creation. If the command fails, you should fix the reported problem(s) and"
echo "run rock-create-orogen again until it passes."
echo
echo "Once there are no errors left, run then"
echo "  amake"
echo "to build and install the package"
echo
