#!/bin/bash


COURSESHELL_NAME=$(cat /usr/local/bin/courseshell.name)


function print_usage_message()
{
    echo "Usage:"
    echo
    echo "$COURSESHELL_NAME PROJECT_NAME TEMPLATE_NAME [ENVIRONMENT_PATH]"
    echo
    echo "    Starts a new project from the specified template.  The new"
    echo "    project will appear in the ~/projects directory.  Alternatively,"
    echo "    the path to the environment directory can also be specified."
    echo
}


if [ $# -ne 2 ] && [ $# -ne 3 ]; then
    print_usage_message
    exit 1
fi


PROJECT_NAME=$1

if [ $# -eq 3 ]; then
    ENVIRONMENT_DIR=$(readlink -m $3)
else
    ENVIRONMENT_DIR=$(readlink -m ~/environment)
fi

TEMPLATES_DIR=$ENVIRONMENT_DIR/templates
PROJECTS_DIR=$(readlink -m ~/projects)


TEMP_DIR=$(mktemp -d)

function cleanup()
{
    rm -rf $TEMP_DIR
}

set -e
trap cleanup exit


if [ -e $PROJECTS_DIR/$PROJECT_NAME ]; then
    echo "The project $PROJECT_NAME already exists in your ~/projects directory."
    echo
    exit 1
fi


if [ -e $2 ] && [ ! -d $2 ]; then
    SRC_TARBALL=$(readlink -m $2)

    cd $TEMP_DIR
    tar xfz $SRC_TARBALL

    if [ -e $TEMP_DIR/.template ]; then
        TEMPLATE_NAME=$(head -1 $TEMP_DIR/.template)
    else
        TEMPLATE_NAME=basic
    fi

    if [ ! -e $TEMPLATES_DIR/$TEMPLATE_NAME ]; then
        echo "The file $SRC_TARBALL contains code from a project built using the template"
        echo "$TEMPLATE_NAME, but that template does not exist."
        echo
        echo "These are the available tempaltes:"
        ls -1 $TEMPLATES_DIR
        echo
        echo "If you expect this template to exist, it might be because you haven't"
        echo "updated your environment."
        echo
        exit 1
    fi

    mkdir -p $PROJECTS_DIR/$PROJECT_NAME
    cp -r $TEMPLATES_DIR/$TEMPLATE_NAME/* $PROJECTS_DIR/$PROJECT_NAME
    cp -r $TEMP_DIR/src/* $PROJECTS_DIR/$PROJECT_NAME/src
    echo -n $TEMPLATE_NAME >$PROJECTS_DIR/$PROJECT_NAME/.template

    echo "The project $PROJECT_NAME has been created from the file $SRC_TARBALL,"
    echo "using the template $TEMPLATE_NAME specified in that file."
    echo "It is ready to be used in this directory: ~/projects/$PROJECT_NAME"
    echo
else
    TEMPLATE_NAME=$2

    if [ ! -e $TEMPLATES_DIR/$TEMPLATE_NAME ]; then
        echo "The template $TEMPLATE_NAME does not exist."
        echo
        echo "These are the available templates:"
        ls -1 $TEMPLATES_DIR
        echo
        echo "If you expect this template to exist, it might be because you haven't"
        echo "updated your environment."
        echo
        exit 1
    fi

    mkdir -p $PROJECTS_DIR/$PROJECT_NAME
    cp -r $TEMPLATES_DIR/$TEMPLATE_NAME/* $PROJECTS_DIR/$PROJECT_NAME
    echo -n $TEMPLATE_NAME >$PROJECTS_DIR/$PROJECT_NAME/.template

    echo "The project $PROJECT_NAME has been created from the template $TEMPLATE_NAME."
    echo "It is ready to be used in this directory: ~/projects/$PROJECT_NAME"
    echo
fi

