#!/bin/sh

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

usage_message() {
  echo "Usage: set_makefile <project name>"
  echo ""
  echo "        <project name>: Name of the main tex file (without .tex)"
  echo "        <project name>.mak should exist"
}

if [ -z "$1" ]; then
  echo "$0: Syntax Error - Project name Missing"
  usage_message
  exit 1
fi

PROJECT_NAME="$1"
NEW_MAKEFILE="${PROJECT_NAME}.mak"
MAKEFILE="Makefile"

if [ ! -e "${NEW_MAKEFILE}" ]; then
  echo "$0: Error: new makefile ${NEW_MAKEFILE} does not exist"
  usage_message
  exit 1
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}"
