USAGE="Usage: $0 templateName applicationName"

RELSCRIPTPATH="$(realpath "$0")"
SCRIPTPATH="$(
  cd "$(dirname "${RELSCRIPTPATH}")" >/dev/null 2>&1
  pwd -P
)"
source "${SCRIPTPATH}/env"

export BUILDTEMP="/tmp/nobj-build"

function templates() {
  echo ""
  echo "Available templates:"
  ls -1 "${TOOLROOT}/templates/app/"
  echo ""
}

###########################

TEMPLATEROOT=${TOOLROOT}/templates/app/

if [[ ! -d ${TEMPLATEROOT} ]]; then
  echo "! No installed templates. Use nobj-build-update to fetch them."
  exit 1
fi

if [[ -z $1 ]]; then
  echo "${USAGE}"
  templates
  exit 1
fi

TEMPLATE=$1

CURRENTTEMPLATE=${TEMPLATEROOT}/${TEMPLATE}

if [[ ! -d ${CURRENTTEMPLATE} ]]; then
  echo "! Template ${TEMPLATE} not found"
  echo ""
  templates
  exit 50
fi

APPNAME=$2

if [[ -z $2 ]]; then
  echo "${USAGE}"
  exit 2
fi

if [[ -d "${APPNAME}" ]]; then
  echo "! Directory already exists. Stopping!"
  exit 2
fi
if [[ -f "${APPNAME}" ]]; then
  echo "! A file already exists with that name, cannot create a Directory. Stopping!"
  exit 3
fi

echo "- Creating Application ${APPNAME}"

mkdir "${APPNAME}"
mkdir "${APPNAME}/src" "${APPNAME}/css" "${APPNAME}/assets"

if [[ -d "${CURRENTTEMPLATE}/user" ]]; then

  echo "- Populating user files ..."
  cp -a "${CURRENTTEMPLATE}/user/" "${APPNAME}/" 2>/dev/null || {
    echo "- No populated user files."
  }

fi

echo "export TEMPLATE=${TEMPLATE}" >"${APPNAME}/.template"
echo "export TEMPTYPE=app" >>"${APPNAME}/.template"

find "${APPNAME}"
