#! /bin/sh

# make sure we're in a shell that supports pushd & popd
pushd . > /dev/null 2> /dev/null || exec bash "$0"
popd > /dev/null


DIR="$(dirname "$0")"
pushd "$DIR" > /dev/null &&
if [ -x /bin/pwd ]; then
  DIR="$(/bin/pwd)"
else
  DIR="${PWD}"
fi &&
popd > /dev/null || exit $?

# ignore any setting from environment
export ACL2_SYSTEM_BOOKS="${DIR}/books/"

if [ '!' -d "${ACL2_SYSTEM_BOOKS}" ]; then
  echo "Could not find system books directory!"
  exit 1
fi

if [ '!' -e "${ACL2_SYSTEM_BOOKS}saved_dir" ] ||
   [ "$(cat "${ACL2_SYSTEM_BOOKS}saved_dir")" != "$ACL2_SYSTEM_BOOKS" ]; then
  # Need to run fix-cert
  touch "${ACL2_SYSTEM_BOOKS}fix-cert.out" 2> /dev/null
  if [ -w "${ACL2_SYSTEM_BOOKS}saved_dir" ] &&
     [ -w "${ACL2_SYSTEM_BOOKS}fix-cert.out" ]; then
    # We can write to stuff.
    echo "New install path detected."
    echo "Fixing .cert files (please be patient & don't kill me) ..."
    pushd "$DIR" > /dev/null
    echo '(ld "fix-cert.lsp")' | #ACL2_CMD# > "${ACL2_SYSTEM_BOOKS}fix-cert.out"
    popd > /dev/null
    if [ "$(cat "${ACL2_SYSTEM_BOOKS}saved_dir")" != "$ACL2_SYSTEM_BOOKS" ]; then
      # Hey!  What happened?
      echo "There seems to have been a problem fixing the .cert files!"
      echo "Here's the full output:"
      cat "${ACL2_SYSTEM_BOOKS}fix-cert.out"
      exit 1
    else
        #touch the compiled files in the new books dir
        echo "Updating timestamps for the compiled files ..."
        java -jar "${DIR}/touch_compiled.jar" "${DIR}"
    fi

    # create new script
    echo "#!/bin/sh" > "${DIR}/saved_acl2" &&
    echo "[ \"\$ACL2_SYSTEM_BOOKS\" ] || export ACL2_SYSTEM_BOOKS=\"$ACL2_SYSTEM_BOOKS\"" >> "${DIR}/saved_acl2" &&
    echo "echo '==> This saved_acl2 script is for compatibility with Makefiles, etc.     <=='" >> "${DIR}/saved_acl2" &&
    echo "echo '==> Use run_acl2 instead to automatically detect & adapt to being moved. <=='; echo" >> "${DIR}/saved_acl2" &&
    echo "DIR=\"$DIR\"" >> "${DIR}/saved_acl2" &&
    echo '#ACL2_CMD#' >> "${DIR}/saved_acl2" || exit 1

    echo "Done.  Continuing to execute ACL2..."
  else
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    echo "! WARNING: It appears ACL2 is in a new path, but I'm not allowed"
    echo "! to write to files in $DIR"
    echo "! to fix the .cert files for the standard books.  I'll let you"
    echo "! continue, but you might have trouble using the standard books."
    echo "! To fix, run ${DIR}/run_acl2"
    echo "! with the appropriate privileges."
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  fi
fi

exec #ACL2_CMD#
