#!/bin/sh

error() {
   echo "Configure failed due to the errors above!"
   exit 1
}

if [ "$1" = "--help" -o "$1" = "-help" -o "$1" = "-h" -o "$1" = "-H" ]; then 
   # dont check for updates if only the usage statement is requested
   echo ""
elif [ "$1" = "--no-updates" ]; then
   # escape flag to avoid checking for patches
   echo "Skipping check for Amber updates"
   shift
else
   # Tell people we're checking for updates, since this could take a
   # couple seconds, especially if ambermd.org is down
   echo "Checking for updates..."

   # Check to see if there are any updates available. This will print a message
   # giving how many patches are available for Amber and AmberTools
   ./patch_amber.py --check-updates

   # The return code of the above command tells us what happened. Return 1 for
   # an error, and return 2 if there are patches available
   ret_code=$?

   if [ $ret_code -eq 2 ]; then
      echo "There are patches available. Do you want to apply them now? [y/n] (Recommended Y)"
      read answer

      if [ "$answer" = "yes" -o "$answer" = "Yes" -o "$answer" = "YES" -o "$answer" = "y" -o "$answer" = "Y" ]; then
         # Since patch_amber may patch itself and quit before applying all patches,
         # continue to check for updates and update the tree until they have all
         # been applied.
         while [ $ret_code -eq 2 ]
         do
            ./patch_amber.py --update-tree
            if [ $? -ne 0 ]; then
               echo "Automatic patching failed! Check the errors before re-configuring"
               exit 1
            fi
            ./patch_amber.py --check-updates 2>&1 > /dev/null
            ret_code=$?
         done
      else
         echo "NOT updating your tree and continuing anyway."
      fi
   elif [ $ret_code -eq 1 ]; then
      echo "Check for updates failed."
   fi
fi

# Simple redirection to carry out the configure script inside AmberTools/src

(cd AmberTools/src && ./configure2 $@) || error

# Bail out if we just got the usage statement
if [ $# -lt 1 ]; then
   exit 0
elif [ $# -eq 1 ]; then
   if [ "$1" = "--help" -o "$1" = "-help" -o "$1" = "-h" -o "$1" = "-H" ]; then
      exit 0
   fi
fi

ln -sf AmberTools/src/config.h .

# Make clean here

echo "Cleaning the src directories. This may take a few moments."
make clean > /dev/null 2>&1
echo "Configure complete."
