#!/bin/sh
# 2023-09-21:  Better error message if no template directory can be found.
# 2018-07-30:  Fixed to handle a template directory that is a symlink.

if [ $# = 0 ]; then
  echo
  echo "Usage: mkws <workspace name>"
  echo
  echo "Description: Creates a new workspace by copying a template workspace."
  echo
  exit 1
fi

dir=$1

if [ -f $dir -o -d $dir ]; then
  echo "" >&2
  echo "Directory $dir already exists." >&2
  echo "" >&2
  exit 1
fi

if [ "$GIANT_DIR" = "" ]; then
  export GIANT_DIR=/opt/giant
fi

template_dir1=""
template_dir2=~/Documents/giant/workspace/template
template_dir3=${GIANT_DIR}/share/workspace/template

if [ "$GIANT_DATA_DIR" != "" ]; then
  template_dir1=${GIANT_DATA_DIR}/../template
fi

template_dir=$template_dir1

if [ "$template_dir" = "" -o ! -d "$template_dir" ]; then
  template_dir=$template_dir2
fi

if [ ! -d "$template_dir" ]; then
  template_dir=$template_dir3
fi

if [ ! -d "$template_dir" ]; then
  echo "" >&2
  echo "Could not locate a template directory in the following locations:" >&2

  if [ "$template_dir1" != "" ]; then
    echo "  $template_dir1" >&2
  fi

  echo "  $template_dir2" >&2
  echo "  $template_dir3" >&2
  echo >&2
  echo "You will need to create a template directory in one of these" >&2
  echo "locations which contains all the files and directories that you" >&2
  echo "want to have in new workspaces." >&2
  echo >&2
  echo "Aborting." >&2
  echo "" >&2
  exit 1
fi

echo ""
echo "Creating workspace based upon template directory:"
echo "  $template_dir"
echo ""
cp -a $template_dir/. $dir
