#!/bin/sh
# export KEEPTEMPDIR=1

home_dir=${PWD}

project_name="ProjectTest"
version="1.0"
module_name="ModuleTest"
module_dep_name="Alexandria"

# Create a unique directory
tmploc=$(mktemp -dq -t temp.XXXXXX)

# Set to the User_area
cd ${tmploc}
export User_area=${tmploc}

# Clean and exit
local_clean_exit() {
  cd ${home_dir}
  if [ -z "${KEEPTEMPDIR}" ]; then
    rm -rf ${tmploc}
  fi
  
  exit $1
}

# We need first to create a project
CreateElementsProject $project_name $version --yes

# Error? stop and clean up
if [ $? -ne 0 ]; then
   echo "Error: <CreateElementsProject $project_name $version> command failed!" 1>&2
   local_clean_exit 1
fi

# Move to the project
cd $User_area/$project_name/$version/

# Create a module
AddElementsModule $module_name -md $module_dep_name --yes

# Error? stop and clean up
if [ $? -ne 0 ]; then
   echo "Error: <AddElementsModule $module_name -md $module_dep_name> command failed!" 1>&2
   local_clean_exit 1
fi

# Make sure the module is created
if [ ! -d $module_name ]; then
   echo "Error: <AddElementsModule $module_name -md $module_dep_name> command failed!" 1>&2
   local_clean_exit 1
fi

module_path="$User_area/$project_name/$version/$module_name"

# Make sure <CMakeLists.txt> file has been created
if [ ! -e $module_path/CMakeLists.txt ]; then
   echo "Error: <$module_path/CMakeLists.txt> file not found!" 1>&2
   local_clean_exit 1
fi

# Make sure the <module_test> is there
result=$( grep "elements_subdir" $module_path/CMakeLists.txt | grep "$module_name" )
if [ $? -ne 0  ];then
   echo "Error: <elements_subdir> macro with <$module_name> module not found!" 1>&2
   local_clean_exit 1
fi

# Make sure the <ElementsKernel> is there
result=$( grep "elements_depends_on_subdirs" $module_path/CMakeLists.txt |
          grep -v "#" | grep "ElementsKernel" )
if [ $? -ne 0  ];then
   echo "Error: <elements_depends_on_subdirs> macro with <ElementsKernel> module not found!" 1>&2
   local_clean_exit 1
fi

# Make sure the <Alexandria> is there
result=$( grep "elements_depends_on_subdirs" $module_path/CMakeLists.txt |
          grep -v "#" | grep $module_dep_name )
if [ $? -ne 0  ];then
   echo "Error: <elements_depends_on_subdirs> macro with <$module_dep_name> dependency not found!" 1>&2
   local_clean_exit 1
fi

# Make sure directories are created
if [ ! -d $module_path/conf ] || [ ! -d $module_path/doc ] || [ ! -d $module_path/tests/src ]; then
   echo "Error: <$module_path/conf or $module_path/doc or $module_path/tests/src> directory not found!" 1>&2
   local_clean_exit 1
fi

local_clean_exit 0
