#!/bin/sh

#
# set_makefile: set the currently active project (the symlink to Makefile)
#

usage_message() {
  echo "$0: set latex_make makefile"
  echo ""
  echo "Usage:"
  echo "       set_makefile [<PROJECT_NAME>]"
  echo ""
  echo "  Where <PROJECT_NAME> is the name of your project."
  echo "  This means that your makefile is <PROJECT_NAME>.mak"
  echo "  and your main tex file is <PROJECT_NAME>.tex"
  echo ""
  echo "  if <PROJECT_NAME> is not given, and only one *.mak file,"
  echo "  exists in the current directory then it will be used as "
}

# I don't assume PROJECT_NAME is non-empty. Only the value of 
# NEW_MAKEFILE is used in the rest of the script
project_name="$1"
NEW_MAKEFILE="${PROJECT_NAME}.mak"
MAKEFILE="Makefile"

case "$1" in
  -h|--help)
    usage_message;
    exit 
    ;;
# TODO:
# -s|--select)
# add here some code to choose makefle interactively
  *)
    # Continue
esac

if [ ! -e "${NEW_MAKEFILE}" ]; then
  current_makefiles="`ls *.mak 2>/dev/null`"
  first_makefile="`ls *.mak 2>/dev/null| head -n 1`"
  if [ -z "${current_makefiles}" ]; then
    echo "$0: Error: new makefile ${NEW_MAKEFILE} does not exist"
    usage_message
    exit 1
  fi
  if [ "${first_makefile}" = "${current_makefiles}" ]; then
    # There is only one makefile in the current directory
    echo "Only one makefile in the current directory (${first_makefile})"
    NEW_MAKEFILE="${first_makefile}"
  else
    # More than one makefile
    echo "ERROR: More than one makefile in current directory."
    echo "       You'll have to tell me which of them you want:"
    echo ""
    for makefile in ${current_makefiles}; do
      proj="`basename ${makefile} .mak`"
      echo "   $0 ${proj}"
    done
    echo ""
    echo "or use \"$0 --help\" for the full help message"
    exit 1
  fi
fi

if [ ! -f "${NEW_MAKEFILE}" ]; then
  echo "$0: Warning: new makefile ${NEW_MAKEFILE} is not a regular file"
fi

# Makefile should be a symlink!
if [ -e "${MAKEFILE}" ]; then
  # Makefile should be a symlink!
  if [ ! -L "${MAKEFILE}" ]; then
    echo "$0: Error: ${MAKEFILE} is not a symbolic link."
    echo "     I don\'t want to replace it with a link to ${NEW_MAKEFILE}"
    echo "     Bailing out"
    exit 1
  fi
  
  # if it is a symlink, it can be safely removed 
  rm -f "${MAKEFILE}" 
fi

# If we got to this point, ${MAKEFILE} does not exist (perhaps deleted, and
# can be safely created

# added -v to make the user aware of what happened.
ln -sv "${NEW_MAKEFILE}" "${MAKEFILE}"
